使用angular将多维数组转换为使用php和usort的多级列表

时间:2012-10-24 13:35:16

标签: php

我一直在研究这个问题。我看到php中的多级数组并不那么容易。这是我的代码:

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()

1 个答案:

答案 0 :(得分: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');