phparrayssortingmultidimensional-arraypreserve

Sort a multidimensional array descending by subarray count and preserve first level keys


I have an array such as:

$array = [
    'DEF' => [
        ['type' => 1, 'id' => 1212, 'name' => 'Jane Doe', 'current' => 1],
        ['type' => 1, 'id' => 3123121, 'name' => 'Door', 'current' => null],
    ],
    'ABC' => [
        ['type' => 1, 'id' => 1234, 'name' => 'John Doe', 'current' => null],
    ],
    'WW' => [
        ['type' => 1, 'id' => 1212, 'name' => 'Jane Doe', 'current' => 1],
        ['type' => 1, 'id' => 3123121, 'name' => 'Door', 'current' => null],
        ['type' => 1, 'id' => 64646, 'name' => 'Floor', 'current' => null],
    ]
];

And I want to sort this array by number ( count() ) of inner-array items descending (i.e. most items first), so I will have this array:

[
    'WW' => [
        ['type' => 1, 'id' => 1212, 'name' => 'Jane Doe', 'current' => 1],
        ['type' => 1, 'id' => 3123121, 'name' => 'Door', 'current' => null],
        ['type' => 1, 'id' => 64646, 'name' => 'Floor', 'current' => null],
    ],
    'DEF' => [
        ['type' => 1, 'id' => 1212, 'name' => 'Jane Doe', 'current' => 1],
        ['type' => 1, 'id' => 3123121, 'name' => 'Door', 'current' => null],
    ],
    'ABC' => [
        ['type' => 1, 'id' => 1234, 'name' => 'John Doe', 'current' => null],
    ]
];

Can anyone suggest an efficient way to do so? Thanks.


Solution

  • Using uksort:

    uksort($array, function($a, $b) { return count($b) - count($a); });
    

    Using array_multisort:

    array_multisort(array_map('count', $array), SORT_DESC, $array);
    

    With PHP < 5.3:

    function sort_cb($a, $b) {
        return count($b) - count($a);
    }
    uksort($array, 'sort_cb');