假设我有以下数组:
Array
(
[0] => Array
(
[id] => 5
[name] => Education
[parent] => 1
[sort_order] => 3
[leaf] => 1
)
[1] => Array
(
[id] => 6
[name] => Computers
[parent] => 1
[sort_order] => 1
[leaf] => 1
)
[2] => Array
(
[id] => 7
[name] => Science
[parent] => 1
[sort_order] => 2
[children] => Array
(
[0] => Array
(
[id] => 8
[name] => Mathematics
[parent] => 7
[sort_order] => 2
[children] => Array
(
[0] => Array
(
[id] => 11
[name] => Geometry
[parent] => 8
[sort_order] => 2
[leaf] => 1
)
[1] => Array
(
[id] => 12
[name] => Algebra
[parent] => 8
[sort_order] => 1
[leaf] => 1
)
)
)
[1] => Array
(
[id] => 9
[name] => Physics
[parent] => 7
[sort_order] => 1
[leaf] => 1
)
[2] => Array
(
[id] => 10
[name] => Biology
[parent] => 7
[sort_order] => 4
[leaf] => 1
)
[3] => Array
(
[id] => 13
[name] => History
[parent] => 7
[sort_order] => 3
[leaf] => 1
)
)
)
是否有任何PHP内置函数会在每个级别上按'sort_order'
值分别对此数组进行排序?我找到了几个sollutions,但是所有这些都按字母顺序排序或使用了ksort()。
可能需要递归,但我需要一些帮助如何开始。 TIA。
答案 0 :(得分:0)
有一个:usort
它允许你构建比较函数。
什么是比较功能?一个函数接受两个参数,当第一个小于第二个时返回-1,第一个大于时为+1,如果两个相等则返回0。
如何定义函数?
如果有内置函数或带有函数的personnal函数,那么代表函数名的字符串就是点。
如果它是对象的方法,则必须使用带有对实例和方法名称的引用的数组
至少,你可以使用这样的匿名函数:
function sortALevel(&$array){
usort($array,function($a,$b){
if($a['sort_order'] > $b['sort_order']){
return 1;
}
if($a['sort_order'] < $b['sort_order']){
return -1;
}
return 0;
});
}
function sort_recursive($array){
sortALevel($array);
foreach($array as $value){
if(is_array($value)){
sort_recursive($value);
}
}
}