多维数组 - 按月分组
I'm trying to wade my way through working more with multidimensional arrays to decrease the number of SQL queries I'm having to make. The problem is, they are new to me. Can someone give me some direction how to accomplish this?
Here's an example of the array:
Array
(
[0] => Array
(
[0] => 2013-07-01
[1] => Andy
[2] => Hopkins Module
)
[1] => Array
(
[0] => 2013-07-01
[1] => Frank
[2] => Rotation
)
[2] => Array
(
[0] => 2013-07-01
[1] => James
[2] => Morning Report
)
[3] => Array
(
[0] => 2013-08-01
[1] => James
[2] => Noon Conference
)
This array continues on with a lot more names and months. The data is ordered by name, meaning all of James item's are listed in a group. Each group of names may have one or more data points. What I would like to do is loop through each month and print out the second and third values. I know how to do a while statement to print out everything, but I'm not sure how to group all of the data by month.
Give this a try (it assumes the array you showed is assigned to the variable $old_array
):
foreach ($old_array as $key => $value) {
$new_array[$value[0]][] = array($value[1], $value[2]);
}
// Uncomment the next line to print the new array
// print_r($new_array);
I was able to do it with a modified version of jerdiggity's code... and the only way I could get it to work is terribly ugly. Are these many nested loops common?
foreach ($incomplete as $key => $value) {
$new_array[$value[0]][$value[1]][] = $value[2];
}
foreach($months as $k=>$v) {
$format = formatDate($v);
echo $format; // date formatted as readable
foreach($new_array[$format] as $k1=>$v1){
echo $k1.'<br>'; //name of person
foreach($v1 as $k2=>$v2) {
echo $v2.'<br>'; //third value or original array
}
}
}