views:

108

answers:

2

Trying to sort this array of objects according to (1) depth and (2) weight, and am unsure how to modify the function I'm using to include this other level...

I'm using this function:

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

And then doing this:

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

And that will accurately sort the array according to weight, but I need to add in another level of sorting. So that the array is first sorted according to depth, and then by weight.

So that, 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
        )
+1  A: 
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;
}
konforce
perfect, thanks
phpN00b
+1  A: 

when comparing numbers, you can simply subtract them

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