按特定键对多维数组递归进行排序


Sort multidimensional array recursive by specific key

我正在尝试按标签递归地对这个数组进行排序:

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

子元素未排序...

看看这个:

为了能够直接修改循环中的数组元素,前面$value &.在这种情况下,该值将通过引用分配。(摘自: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');
}