0

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] => 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
        )
)
Andy Hayden
  • 359,921
  • 101
  • 625
  • 535
BentCoder
  • 12,257
  • 22
  • 93
  • 165

4 Answers4

0

I assume that there is no simple function to accomplish that so I've come up with this code:

arsort($file_list);

foreach ($file_list as $key => $inner_array)
{
    krsort($inner_array);
    $file_list[$key] = $inner_array;
}

echo '<pre>'; print_r($file_list);
BentCoder
  • 12,257
  • 22
  • 93
  • 165
0

This should work

foreach ($arr as &$ar) { arsort($ar); }

http://codepad.org/ne2ldv9w

air4x
  • 5,618
  • 1
  • 23
  • 36
0

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>
enenen
  • 1,967
  • 2
  • 17
  • 33
  • Thanks. Also, why `Arsort` will not sort your array properly? Any technical problem? – BentCoder Nov 06 '12 at 13:22
  • There is not a technical problem. You can check PHP Doc for more details and try @air4x's snippet (http://codepad.org/ne2ldv9w) to see that the sorting is not proper with `arsort`. – enenen Nov 06 '12 at 13:32
  • Sorry, I didn't see that you want to sort in DESC order. Edited my answer. Just change `ksort` with `krsort` instead. – enenen Nov 06 '12 at 13:36
0

Run the following code:

array_walk($array,'krsort');
Notepad
  • 1,659
  • 1
  • 12
  • 14