Multidimensional Array- Grouping by month

依然范特西╮ 提交于 2020-01-06 13:54:26

问题


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.


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/19072804/multidimensional-array-grouping-by-month

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!