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

471

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

Answer

Solution:

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 thatisset($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;

People are also looking for solutions to the problem: php - var_dump array returning my string, double?

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.