我试图通过其标签递归地对此数组进行排序:
Array
(
[0] => Array
(
[id] => 6
[label] => Bontakt
[children] => Array
(
)
)
[1] => Array
(
[id] => 7
[label] => Ampressum
[children] => Array
(
[0] => Array
(
[id] => 5
[children] => Array
(
)
[label] => Bome
)
[1] => Array
(
[id] => 8
[children] => Array
(
)
[label] => Aome
)
[2] => Array
(
[id] => 10
[children] => Array
(
)
[label] => Come
)
)
)
[2] => Array
(
[id] => 9
[label] => Contakt
[children] => Array
(
)
)
[3] => Array
(
[id] => 11
[label] => Dead
[children] => Array
(
)
)
)
我已经阅读了几个问题,我觉得非常接近,但我无法弄清楚哪些问题无效:
function sortByAlpha($a, $b)
{
return strcmp(strtolower($a['label']), strtolower($b['label'])) > 0;
}
function alphaSort(&$a)
{
foreach ($a as $oneJsonSite)
{
if (count($oneJsonSite["children"]) > 0) alphaSort($oneJsonSite["children"]);
}
usort($a, 'sortByAlpha');
}
alphaSort($jsonSites);
当前输出是这样的:
Ampressum
Bome
Aome
Come
Bontakt
Contakt
Dead
子元素未排序......
答案 0 :(得分:1)
检查出来:
为了能够直接修改循环中的数组元素,在$ value之前加上&amp ;.在这种情况下,该值将通过引用分配。 (从这里挑选:http://php.net/manual/en/control-structures.foreach.php)
你应该试试这个:
function alphaSort(&$a)
{
foreach ($a as &$oneJsonSite)
{
if (count($oneJsonSite["children"]) > 0) alphaSort($oneJsonSite["children"]);
}
usort($a, 'sortByAlpha');
}