Home » Php » sorting – Sort Multidimensional Array with Dynamic Key on Child Value – PHP

sorting – Sort Multidimensional Array with Dynamic Key on Child Value – PHP

Posted by: admin February 25, 2020 Leave a comment

Questions:

I have a 4 dimensional associative array, with all of its key dynamic. I want to sort the array on the value of its last child.
For a reference, this is the array:

$array = array(
    "Africa" => array(
        "Egypt" => array(
            "20" => array(
                "basicInfo" => array('population' => 'xxx', 'size' => 'xxx')
            )
        ),
        "Sudan" => array(
            "249" => array(
                "basicInfo" => array('population' => 'xxx', 'size' => 'xxx')
            )
        ),
        ...
        ...
    ),
    "Europe" => array(
        "Greece" => array(
            "30" => array(
                "basicInfo" => array('population' => 'xxx', 'size' => 'xxx')
            )
        ),
        "Netherlands" => array(
            "31" => array(
                "basicInfo" => array('population' => 'xxx', 'size' => 'xxx')
            )
        ),
        ...
        ...
    ),
    ...
    ...
);

In the above array, I want to sort on the basis of population in descending order. So far, I’ve tried uasort, array_multisort, but I think I am doing it wrong. Can someone please help me sort this?

uasort($records[$continent][$country][$countryCode]['basicInfo'], array($this, 'sortByPopulation' ));

To be clear, I am sorting it in the for loop while it is being created. Since all the variables inside the array are dynamic, I think it cannot be sorted after generating the array.

The final result should be in the same format as above, continents > countries > codes > basicInfo.

Thank You

How to&Answers:

Assuming you want to sort within continents, this code will do what you want. It iterates over each continent within the array, using a custom sort function to sort on the population value for each country. To deal with the dynamic keys within the country, we use current to get the first element of the array, from which we can then get to basicInfo and then population:

$array = array_map(function ($arr) {
    uasort($arr, function ($a, $b) {
        return current($b)['basicInfo']['population'] - current($a)['basicInfo']['population'];
    });
    return $arr;
}, $array);
print_r($array);

Demo on 3v4l.org

Note that it doesn’t make any sense to sort while you are generating the array as you will still need to sort it after you insert the last value. So just run your loop and then sort…