嵌套php foreach循环


Nested php foreach loop

我有一个foreach循环从这里获取它的信息:

        $eventarray[] = array(          
            "month" => $cal_months[$event_month],           
            "day1" => $event_day1,             
            "title" => $title,            
            "desc" => html_entity_decode($article),
            "month_link" =>   strtolower($event_month),
            "link" => $event_link      
        ); 

对于数组的每次迭代,它都会输出一个事件div,其中包含标题、描述和指向实际事件页面的链接。这样做的问题是,如果同一天有两个事件,那么我就会得到当天每个事件的两个单独的div。我想做的是把事件放在同一个div中,如果它们是在同一天。

我"认为"我必须嵌套第二个foreach循环,但是当我这样做时,错误就出来了。

这就是我所尝试的,我知道这是错误的,但我被卡住了:

foreach($eventarray as $value){
        if($value['month'] == $thismonth){
            $day[] = $value['day1'];
            echo $value['title'];
            echo $value['desc'];
            echo $value['link'];
            foreach($day as $day_value){
                echo 'test';
            }

    }

如果在一天中有多个天,我如何让这些天连接在一起?

你为什么不试试呢?在输入上求解。例如

     $eventarray[$event_day1][] = array(          
        "month" => $cal_months[$event_month],           
        "day1" => $event_day1,             
        "title" => $title,            
        "desc" => html_entity_decode($article),
        "month_link" =>   strtolower($event_month),
        "link" => $event_link      
    ); 

做到这一点的简单方法不是使用嵌套的foreach,而是使用两个foreach循环,一个接一个。在第一个示例中,将当天的事件放入一个新数组中,在第二个示例中,打印该数组。

// This will actually be a 2-dimensional array
$events_by_day = array();
// Get this month's events and group by day.
foreach($eventarray as $value){
    if($value['month'] == $thismonth){
        // Push this event into the $events_by_day[<DAY>] array
        $events_by_day[$value['day1']][] = $value;
    }
}
// For each day, print it.
foreach($events_by_day as $day => $events_today){
    if (count($events_today) > 0){
        echo '<div>';
        echo "$month $day";
        // Get today's events
        foreach($events_today as $event){
            echo $event['title'];
            echo $event['desc'];
            echo $event['link'];
        }
        echo '</div>';
    }
}

它需要一些格式化,但是你明白了。