Sorting and grouping a mutlidimensional array in php
I need some help with sorting a multidimensional array in php. I need the array to be grouped into months, and then sorted by month. Here's my original array:
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
)
)
And here's what I'm hoping to get:
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
)
)
)
I would use an easily sortable key for each month-container, then just use ksort
$months = array();
foreach ($input_array AS $arr) {
$months[$arr['Month']][] = $arr;
}
ksort($months);
if you want, you can then use array_values
to turn it into a standard integer-key array
Maybe, just maybe something like this:
$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);
- Totally untried, untested, exprerimental and from the top of my head.
- You may need SORT_NUMERIC instead of SORT_ASC, I ain't sure.
精彩评论