简体   繁体   中英

Php inside foreach loop if $i == 1 echo “ok”, else echo “ok” JUST one time and continue

its been a while (5 years) since my last time here making questions.

I need help, I'm developing an event calendar and I'm stuck in this. I want to have event header and event body, so far so good, but I just want one header if there are more than one event in each day. So today I've a dinner at 21h, my event should have Friday , November 23 and Dinner at 21h. Perfect, I can do this, but what about if I do have a meeting before dinner, at 19h? I want just one time the same header ... Friday, November 23 but 2 bodies...

thanks!

my piece of code

foreach($eventos[$data_do_dia] as $evento) {
    $i = count($eventos[$data_do_dia]);
    if($i == 1) {
       $agenda .= " dia ".date("d-m-Y",strtotime($evento['dia']))."</b>";
       add the event
    } else {
        repeat the same but just one time
        $agenda .= " dia ".date("d-m-Y",strtotime($evento['dia']))."</b>";

        add event one
        add event two
        ...     
    }
}

I've changed the loop so that there isn't any repeated code, this basically means that if there is only one event, it converts into an array, assuming that isset($evento[0]) will pick up there aren't sub-arrays, it wraps the one entry into a new array.

It then loops over the array and creates the string with the date/time/details. You will probably want to change the format, but the principle is the same...

$agenda = "";
foreach($eventos as $evento) {
    if ( !isset($evento[0]) )    {
        $evento = [$evento];
    }
    $agenda .= " dia ".date("d-m-Y",strtotime($evento[0]['dia'])).PHP_EOL;
    foreach ( $evento as $time )    {
        $agenda .= " time ".$time['hora']." ".
            $time['titulo']." ".$time['evento'].PHP_EOL;
    }
}
echo $agenda;

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