简体   繁体   中英

Sort multidimensional array recursive by specific key

I'm trying to sort this array recursively by its label:

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
                (
                )

        )

)

I've read several Questions, and I feel to be pretty close, but I can't figure out what's not working:

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);

Current output is like this:

Ampressum
    Bome
    Aome
    Come
Bontakt
Contakt
Dead

The children elements are not sorted...

Check this out:

In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference. (Picked from here: http://php.net/manual/en/control-structures.foreach.php )

You should try it with this one:

function alphaSort(&$a)
{
    foreach ($a as &$oneJsonSite)
    {
        if (count($oneJsonSite["children"]) > 0) alphaSort($oneJsonSite["children"]);
    }

    usort($a, 'sortByAlpha');
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM