Search code examples
phpsortingmultidimensional-arraysub-array

Sort a multi-dimensional array by the size of its sub-arrays


I have this multidimensional array:

Array
(
    [0] => Array
        (
        [0] => 2012-02-26 07:15:00
        )
    [1] => Array
        (
            [0] => 2012-02-26 17:45:00
            [1] => 2012-02-26 18:55:00
        )
    [2] => Array
        (
            [0] => 2012-02-26 18:55:00
            [1] => 2012-02-26 17:45:00
        )
    [3] => Array
        (
            [0] => 2012-02-26 18:57:00
            [1] => 2012-02-26 17:45:00
            [2] => 2012-02-26 18:55:00
        )

When I count subarrays I get this 1,2,2,3. How could I receive it in 3,2,2,1? I need to get for example last 3 subarrays with the highest subarray count (DESC, it means 3,2,2). How can I achieve this?


Solution

  • You can achieve it by utilizing usort function.

    function cmp($a, $b){
        return (count($b) - count($a));
    }
    usort($array, 'cmp');
    $highest_3_sub_arrays = array_slice($array, 0, 3);