php - Using usort() to sort a 2-dimensional array with hierarchical ordering criteria -


trying sort 2-dimensional array of pizza toppings category of topping belongs to. way client supplies data isn't ideal this. here's sample of data:

        [0] => array             (                 [id] => 30                 [title] => pepperoni                 [meat] => 1                 [veggie] =>                  [sauce] =>                  [cheese] =>                  [condiment] =>              )          [1] => array             (                 [id] => 29                 [title] => onions                 [meat] =>                  [veggie] => 1                 [sauce] =>                  [cheese] =>                  [condiment] =>              ) 

the idea toppings should grouped type (ie. meat) in specific order (ie. meats followed veggies followed sauces , on)—independent of order in they're retrieved. importantly, no topping ever belongs 2 types.

here's stab @ this:

$topping_options = array()  // ie. sample data above usort($topping_options,                 function($opt_a, $opt_b) {                     $scores = array("a" =>  0, "b" => 0);                     foreach( array("a" => $opt_a, "b" => $opt_b) $index => $opt) {                         if ($opt['meat']) $scores[$index] = 5;                         if ($opt['veggie']) $scores[$index] = 4;                         if ($opt['sauce']) $scores[$index] = 3;                         if ($opt['cheese']) $scores[$index] = 2;                         if ($opt['condiment']) $scores[$index] = 1;                     }                      return $scores['a'] - $scores['b'];                 }             ); 

this doesn't @ achieve aims , don't understand why; seems me whenever $opt_a has higher score $opt_b should keep it's position while $opt_b gets sent down rung further comparisons. understand i'm doing wrong. thanks.

  1. i think code correct , problem in test data. reorder them see result
  2. to obtain correct result order, change code

    return $scores['b'] - $scores['a'];