1

我已经为此工作了一段时间。我看到 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()

4

1 回答 1

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');
于 2012-10-24T13:38:18.800 回答