Thursday, 30 August 2018

php foreach loop from a multidimensional array

I have a multidimensional array which I want to display in a foreach loop. I've been looking at lots of tutorials but I haven't been able to make it work yet.

This is my array and foreach loop:
$events = array(
           array( Name => "First Event",
                  Date => "12/13/14",
                  Time => "12:13"
                  Description => "event description"
                ),
           array( Name => "Second Event",
                  Date => "12/13/14",
                  Time => "12:13",
                  Description => "event description"
                ),
           array( Name => "Third Event",
                  Date => "12/13/14",
                  Time => "12:13"
                  Description => "event description"
                )
         );

foreach($events as $event) {
    echo "<div class=\"event\"><strong>";
    echo $event[Name];
    echo "</strong><em>";
    echo $event[Date] . " at " . $event[Time];
    echo "</em><div>";
    echo $event[Description];
    echo "</div></div>";
}

and here is how I want it to display:
<div class="event">
  <strong>Event Name</strong><em>Date at Time</em>
  <div>
    Description
  </div>
</div>

I would appreciate any help you could give. Thanks!

The keys are missing quotes and Time => "12:13" missing comma "," at the end:
<?php
$events = array(
           array( "Name" => "First Event",
                  "Date" => "12/13/14",
                  "Time" => "12:13",
                  "Description" => "event description"
                ),
           array( "Name" => "Second Event",
                  "Date" => "12/13/14",
                  "Time" => "12:13",
                  "Description" => "event description"
                ),
           array( "Name" => "Third Event",
                  "Date" => "12/13/14",
                  "Time" => "12:13",
                  "Description" => "event description"
                )
         );

foreach($events as $event) {
?>
<div class="event">
    <strong><?php echo $event["Name"];?></strong><em><?php echo $event["Date"];?></em>
    <div><?php echo $event["Description"];?></div>
</div>
<?php
}
?>

Output
First Event 12/13/14
event description
Second Event 12/13/14
event description
Third Event 12/13/14
event description

0 comments:

Post a Comment