0

我知道这个问题已经被问过好几次了,但给出的答案对我的情况没有帮助。

我有一个简单的数组,基本上代表月份和年份。数组的唯一目的是跟踪数据库中的事件,我需要知道代表了哪些月份和年份。该数组基本上是:

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

我需要对数组进行排序,以便年份按顺序排列,但同一年中的任何月份也应该进行排序。请参阅下面我想要的输出...

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

如何对该数组进行排序,以便值返回为:

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
    )
}

提前致谢!

4

1 回答 1

5

尝试使用uasort。您可以编写一个自定义函数来对内部键而不是外部键进行排序。

编辑:

事实证明,如果您还想对外部月份进行排序,则需要使用uksort 。这似乎有效:

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

编辑:

如果您只是像上面 Jon 建议的那样更改索引顺序,它会简单得多:

$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);
于 2012-08-15T03:21:35.313 回答