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

时间:2011-06-02 01:54:56

标签: php sorting multidimensional-array grouping

我需要帮助在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
            )
    )

)

2 个答案:

答案 0 :(得分:2)

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

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

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

答案 1 :(得分:1)

也许,也许是这样的:

$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,我不确定。