hellofavision
hellofavision

Reputation: 25

How to loop through a multidimensional array

I have the following PHP array structure:

$set = array();
$set[] = array(
    'firstname' => 'firstname 1',
    'lastname' => 'lastname 1',
    "bio" => array(
        'paragraph 1 of the bio,
        'paragraph 2 of the bio',
        'paragraph 3 of the bio'
    ),
);

I then access the array with the following:

<?php $counter = 0;
while ($counter < 1) :  //1 for now
    $item = $set[$counter]?>  
    <h1><?php echo $item['firstname'] ?></h1>
    <h1><?php echo $item['lastname'] ?></h1>
<?php endwhile; ?>

I'm uncertain how I can loop through the "bio" part of the array and echo each paragraph.

So as a final output, I should have two h1s (first and last name) and three paragraphs (the bio).

How can I go about doing this?

Upvotes: 1

Views: 324

Answers (4)

Teena Thomas
Teena Thomas

Reputation: 5239

Try:

foreach($set as $listitem) {
if(is_array($listitem)) {
 foreach($listitem as $v) //as $set['bio'] is an array
  echo '<h1>' .$v . '</h1>';
} else  
 echo '<p>'.$listitem.'</p>';
} 

Upvotes: 0

Brenton Alker
Brenton Alker

Reputation: 9082

You don't need to use a manual counter, you can use foreach. It's generally the easiest way and prevents off-by-one errors.

Then you need a second inner loop to loop through the bio.

<?php foreach ($set as $item): ?>  
    <h1><?php echo $item['firstname'] ?></h1>
    <h1><?php echo $item['lastname'] ?></h1>
    <?php foreach ($item['bio'] as $bio): ?>
        <p><?php echo $bio; ?></p>
    <?php endforeach; ?>
<?php endforeach; ?>

On a related note; you probably want to look into escaping your output.

Upvotes: 1

petrkotek
petrkotek

Reputation: 4791

Add into the while loop also this:

  <?php foreach ($item['bio'] as $paragraph): ?>
    <p><?php echo $paragraph; ?></p>
  <?php endforeach; ?>

Note that used coding style is not optimal.

Upvotes: 1

Mr. Alien
Mr. Alien

Reputation: 157424

Use foreach loop

foreach($item['bio'] as $listitem) {
   echo $listitem;
}

Upvotes: 3

Related Questions