Php sort an object by two criteria?

Trying to sort this array of objects by depth (1) and (2) by weight, and I'm not sure how to change the function I use to enable this other level ...

I am using this function:

function cmp( $a, $b ) { if( $a->weight == $b->weight ){ return 0 ; } return ($a->weight < $b->weight) ? -1 : 1; } 

And then do the following:

 $menu = get_tree(4, $tid, -1, 2); usort($menu, 'cmp'); 

And it exactly sorts the array by weight, but I need to add another sorting level. So the array is first sorted by depth, and then by weight.

So, if the original array looks like this:

  Array ( [0] => stdClass Object ( [tid] => 24 [name] => Sample [weight] => 3 [depth] => 0 ) [1] => stdClass Object ( [tid] => 66 [name] => Sample Subcategory [weight] => 0 [depth] => 1 ) [2] => stdClass Object ( [tid] => 67 [name] => Another Example [weight] => 1 [depth] => 0 ) [3] => stdClass Object ( [tid] => 68 [name] => Subcategory for Another Example [weight] => 1 [depth] => 1 ) [4] => stdClass Object ( [tid] => 22 [name] => A third example master category [weight] => 0 [depth] => 0 ) 

I can sort it first by depth, then by weight, so that the result looks like this:

 Array ( [0] => stdClass Object ( [tid] => 22 [name] => A third example master category [weight] => 0 [depth] => 0 ) [1] => stdClass Object ( [tid] => 67 [name] => Another Example [weight] => 1 [depth] => 0 ) [2] => stdClass Object ( [tid] => 24 [name] => Sample [weight] => 3 [depth] => 0 ) [3] => stdClass Object ( [tid] => 66 [name] => Sample Subcategory [weight] => 0 [depth] => 1 ) [4] => stdClass Object ( [tid] => 68 [name] => Subcategory for Another Example [weight] => 0 [depth] => 1 ) 
+4
source share
2 answers
 function cmp( $a, $b ) { if ($a->depth == $b->depth) { if($a->weight == $b->weight) return 0 ; return ($a->weight < $b->weight) ? -1 : 1; } else return ($a->depth < $b->depth) ? -1 : 1; } 
+8
source

when comparing numbers you can just subtract them

 function cmp($a, $b) { $d = $a->depth - $b->depth; return $d ? $d : $a->weight - $b->weight; } 
+2
source

Source: https://habr.com/ru/post/1302934/


All Articles