我有一个这样的数组:
array (size=3)
4 =>
array (size=3)
'id' => int 4
'parentId' => int 3
'name' => string 'z' (length=4)
5 =>
array (size=3)
'id' => int 4
'parentId' => int 3
'name' => string 'a' (length=4)
9 =>
array (size=3)
'id' => int 4
'parentId' => int 3
'name' => string 'd' (length=4)
我必须按名称对这个数组进行排序! 目标是,使数组成为以下结构:
array (size=3)
5 =>
array (size=3)
'id' => int 4
'parentId' => int 3
'name' => string 'a' (length=4)
9 =>
array (size=3)
'id' => int 4
'parentId' => int 3
'name' => string 'd' (length=4)
4 =>
array (size=3)
'id' => int 4
'parentId' => int 3
'name' => string 'z' (length=4)
你们有什么聪明的解决方案吗?我试图保存键并且名称属于新数组中的键,并再次迭代ksort'ed数组,并设置新位置:
// Placeholder
$categoryContainer = array();
// Iterate all categories
foreach(self::$categories as $key => $category) {
$categoryContainer[$category['name']] = $key;
}
// Resort by key (category name!)
ksort($categoryContainer);
答案 0 :(得分:2)
您可以使用usort http://php.net/manual/en/function.usort.php
function cmp($a, $b)
{
if ($a == $b) {
return 0;
}
return ($a['name'] < $b['name']) ? -1 : 1;
}
usort($array, "cmp");