2010-03-03 4 views
4

Essayer de trier cette matrice d'objets en fonction de (1) profondeur et (2) poids, et je ne sais pas comment modifier la fonction que j'utilise pour inclure cet autre niveau ...php Trier un objet par deux critères?

J'utilise ceci fonction:

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

Et puis en faisant ceci:

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

Et qui précise trier le tableau en fonction du poids, mais je dois ajouter un autre niveau de tri. Alors que le tableau est d'abord trié en fonction de la profondeur, puis en fonction du poids.

Alors que, si le tableau original ressemble à ceci:

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 
     ) 

je peux trier d'abord par la profondeur, puis en poids afin que le résultat ressemble à ceci:

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 
     ) 

Répondre

8
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; 
} 
+0

parfait, merci – phpN00b

2

lors de la comparaison de nombres, vous pouvez simplement les soustraire

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