简体   繁体   中英

Nested php foreach loop

I have a foreach loop getting it's info from this:

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

For each iteration of the array, it spits out an event div that holds the title, description, and a link to the actual event page. The problem with this is is that if there is are two events on the same day, I get two separate divs for each event on that day. What I would like to do is put the events within the same div if they are on the same day.

I "think" I have to nest a second foreach loop, but when I do that it error's out.

Here's what I'm trying, and I know it's wrong, but I'm stuck:

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

            }


    }

How do I get the days to join together if there are more then one on a single day?

Why dont you try & solve on the input. Ie

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

The simple way to do this is not with a nested foreach , but with two foreach loops, one after the other. In the first one, put the events for the day into a new array, and in the second one, print that array.

// 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>';
    }
}

It needs some formatting, but you get the idea.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM