在php中对多维数组进行排序和分组



我需要一些帮助来对php中的多维数组进行排序。我需要将数组分组为月份,然后按月份排序。这是我的原始数组:

Array
(
    [0] => Array
        (
            [IdEvent] => 5
            [EventName] => Copy of Opening snow weekend
            [Year] => 2011
            [Month] => 08
        )
    [1] => Array
        (
            [IdEvent] => 7
            [EventName] => Copy of Copy of Opening snow weekend
            [Year] => 2011
            [Month] => 07
        )
    [2] => Array
        (
            [IdEvent] => 1
            [EventName] => Opening snow weekend
            [Year] => 2011
            [Month] => 05
        )
    [3] => Array
        (
            [IdEvent] => 6
            [EventName] => Copy of Opening snow weekend
            [Year] => 2011
            [Month] => 05
        )
)

以下是我希望得到的:

Array
(
    [0] => Array (
        [0] => Array
            (
                [IdEvent] => 1
                [EventName] => Opening snow weekend
                [Year] => 2011
                [Month] => 05
            )
        [1] => Array
            (
                [IdEvent] => 6
                [EventName] => Copy of Opening snow weekend
                [Year] => 2011
                [Month] => 05
            )
    )
    [1] => Array (
        [0] => Array
            (
                [IdEvent] => 7
                [EventName] => Copy of Copy of Opening snow weekend
                [Year] => 2011
                [Month] => 07
            )
    )
    [2] => Array (
        [0] => Array
            (
                [IdEvent] => 5
                [EventName] => Copy of Opening snow weekend
                [Year] => 2011
                [Month] => 08
            )
    )
)

我会为每个月的容器使用一个易于排序的密钥,然后只使用ksort

$months = array();
foreach ($input_array AS $arr) {
  $months[$arr['Month']][] = $arr;
}
ksort($months);

如果需要,可以使用array_values将其转换为标准整数键数组

也许,只是可能像这样:

$sortedArray = array();
foreach ($unsortedArray as $key => $row) {
  $month[$key] = $row['month'];
  $year[$key]  = $row['year'];
}
$sortedArray =  array_multisort($year, SORT_ASC, $month, SORT_ASC, $unsortedArray);
  • 完全未经尝试,未经测试,在我的头顶上表现出
  • 你可能需要SORT_NUMERIC而不是SORT_ASC,我不确定

相关内容

  • 没有找到相关文章

最新更新