2012-10-24 49 views
1

我一直在努力。我在php中看到多級數組並不那麼容易。這裏是我的代碼:使用angular將多維數組轉換爲使用php和usort的多級列表

Array 
(
[0]=array(
    "level"=>'Level1', 
    "id"=>1, 
    "title"=>"Home", 
    "order"=>"0" 
    ); 
[1]=array(
    "level"=>'Level1', 
    "id"=>"355", 
    "title"=>"About Us", 
    "order"=>"21" 
); 
[2]=array(
    "level"=>'Level1', 
    "id"=>"10", 
    "title"=>"Test", 
    "order"=>"58" 
); 
[3]=array(
    "level"=>'Level2', 
    "id"=>13, 
    "title"=>"Our Team", 
    "order"=>"11", 
    "parent_id"=>"355" 
); 
    [4]=array(
    "level"=>'Level2', 
    "id"=>12, 
    "title"=>"The In Joke", 
    "order"=>"12", 
    "parent_id"=>"355" 
); 
    [5]=array(
    "level"=>'Level2', 
    "id"=>11, 
    "title"=>"Our History", 
    "order"=>"13", 
    "parent_id"=>"355" 
)); 
> 



    1-Home 
    2-about us 
    3-Our Team 
    4-The In Joke 
    5-Our History 
    6-Test 

我必須多層次父子陣列,需要根據有關結果不明白我怎麼可以使用usort()進行排序。

+3

我們能看到你的代碼(而不只是結果)? – SomeKittens

回答

0

要使用usort()對數組進行排序,您需要編寫自定義排序函數。因爲你想看看用於比較的$array['title']值,你會在你的比較函數使用數組索引:

$array = array(
    array(
     "level"=>'Level1', 
     "id"=>1, 
     "title"=>"Home", 
     "order"=>"0" 
    ), 
    // your additional multidimensional array values... 
); 

// function for `usort()` - $a and $b are both arrays, you can look at their values for sorting 
function compare($a, $b){ 
    // If the values are the same, return 0 
    if ($a['title'] == $b['title']) return 0; 
    // if the title of $a is less than $b return -1, otherwise 1 
    return ($a['title'] < $b['title']) ? -1 : 1; 
} 

usort($array, 'compare');