2010-03-03 4 views
4

(1) 깊이 및 (2) 무게에 따라이 객체 배열을 정렬하려고하고이 다른 레벨을 포함하기 위해 사용하고있는 함수를 수정하는 방법을 모르겠다 ...PHP는 두 가지 기준으로 개체를 정렬합니까?

나는 이것을 사용하고있다. 기능 :이 일을

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

: 그리고

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

그리고 정확하게 무게에 따라 배열을 정렬합니다,하지만 난 분류의 다른 수준에 추가해야합니다. 그래서 배열은 먼저 깊이에 따라 정렬 된 다음 무게에 따라 정렬됩니다.

은 원래의 배열은 다음과 같습니다다면 것을 :

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 
     ) 

내가 깊이에 의해 먼저 정렬 할 수 있습니다, 다음 중량 있도록 결과는 다음과 같습니다

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 
     ) 

답변

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

완벽, 고마워. – phpN00b

2

숫자를 비교할 때 간단히 빼기 만하면됩니다.

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