phparrayssortingmultidimensional-array

Sort the first and second level of a 2d array by numeric keys in DESC order


How can I sort inner array keys in DESC order?

I can sort 11, 12 in DESC order with arsort() but inner array remains same. I tried array_multisort(), usort() and others but without luck.

$array = [
    11 => [
        4 => 'apr11timetable.php',
        8 => 'aug11timetable.php',
        6 => 'jun11timetable.php',
        11 => 'nov11timetable.php',
        10 => 'oct11timetable.php'
    ],
    12 => [
        4 => 'apr12timetable.php',
        8 => 'aug12timetable.php',
        2 => 'feb12timetable.php',
        6 => 'jun12timetable.php',
        10 => 'oct12timetable.php'
    ]
];

Solution

  • You can try with ksort. Arsort will not sort your array properly.

    <pre>
    <?php
    $array = Array(
        11 => Array(
            4 => 'apr11timetable.php',
            8 => 'aug11timetable.php',
            6 => 'jun11timetable.php',
            11 => 'nov11timetable.php',
            10 => 'oct11timetable.php'
        ),
        12 => Array(
            4 => 'apr12timetable.php',
            8 => 'aug12timetable.php',
            2 => 'feb12timetable.php',
            6 => 'jun12timetable.php',
            10 => 'oct12timetable.php'
        )
    );
    
    krsort($array, SORT_NUMERIC);
    
    foreach ($array as &$arr) {    
        krsort($arr, SORT_NUMERIC);
    }
    
    print_r($array);
    ?>
    </pre>