遍历PHP数组 [英] Looping through a PHP array

查看:35
本文介绍了遍历PHP数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有以下PHP数组结构:

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; ?>

我不确定如何遍历数组的"bio"部分并回显每个段落.

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

因此,作为最终输出,我应该有两个h1(名字和姓氏)和三个段落(简历).

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

我该怎么做?

推荐答案

您不需要使用手动计数器,可以使用foreach.通常,这是最简单的方法,可以防止一次关闭的错误.

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.

这篇关于遍历PHP数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆