Looping through a PHP array

ぃ、小莉子 提交于 2021-02-05 08:00:37

问题


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?


回答1:


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.




回答2:


Use foreach loop

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



回答3:


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.




回答4:


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


来源:https://stackoverflow.com/questions/13825117/looping-through-a-php-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!