pogeybait
pogeybait

Reputation: 3145

How do I sort a mulidimensional array in php by the keys?

I know this question has been asked several times but the answers given don't help my situation.

I have a simple array that basically represent the month and year. The only purpose of the array is to keep track of events in a database and I need to know which months and years are represented. The array is basically:

$array[MONTH][YEAR] = 1; //just any value. Don't care about the value.

I need to sort the array so that the years are in order but also any months in the same year should also be sorted. See the output I want below...

$dates[10][2012] = 1;
$dates[1][2011] = 1;
$dates[12][2013] = 1;
$dates[4][2010] = 1;
$dates[6][2009] = 1;
$dates[7][2009] = 1;

How do I sort this array so that the values come back as:

Array
(
    [6] => Array
    (
        [2009] => 1
    )
    [7] => Array
    (
        [2009] => 1
    )
    [4] => Array
    (
        [2010] => 1
    )
    [1] => Array
    (
        [2011] => 1
    )
    [10] => Array
    (
        [2012] => 1
    )
    [12] => Array
    (
        [2013] => 1
    )
}

Thanks in advance!

Upvotes: 0

Views: 89

Answers (1)

DaoWen
DaoWen

Reputation: 33019

Try using uasort. You can write a custom function to sort on the inner keys rather than the outer ones.

EDIT:

It turns out that you need to use uksort if you want to sort the outer months as well. This seems to work:

uksort($dates, function ($a, $b) use ($dates) {
  $year = key($dates[$a]) - key($dates[$b]);
  $month = $a - $b;
  return $year == 0 ? $month : $year;
});

EDIT:

If you just change the index order like Jon suggested above it's a lot simpler:

$dates[2012][10] = 1;
$dates[2011][1] = 1;
$dates[2013][12] = 1;
$dates[2010][4] = 1;
$dates[2009][7] = 1;
$dates[2009][6] = 1;

ksort($dates);
array_walk($dates, ksort);

print_r($dates);

Upvotes: 5

Related Questions