我已经在这方面工作了一段时间。我发现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()。
发布于 2012-10-24 21:38:19
要使用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');https://stackoverflow.com/questions/13050409
复制相似问题