douguanyan9928
2013-09-28 23:31
浏览 42
已采纳

多维数组 - 按月分组

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.

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dongmimeng5500 2013-09-28 23:55
    已采纳

    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);
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • dougong8012 2013-09-29 00:33

    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
                }
            }
        }
    
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题