简体   繁体   English

在PHP中将两个foreach循环合二为一?

[英]Two foreach loops into one in PHP?

Given the following: 给定以下内容:

$arrayone = array('Title one', 'Title two');
$arraytwo = array('Content one', 'Content two');

How would I go about out putting the following: 我将如何解决以下问题:

<h2>Title one</h2>
<p>content one</p>

<h2>Title two</h2>
<p>content two</p>

I could do a nested foreach like so: 我可以像这样做一个嵌套的foreach:

foreach ($arrayone as $key => $value) {
    echo "<h4>$value</h4>";
    foreach ($arraytwo as $keysub => $valuesub) {
        # code...
        if($keysub === $key) {
            echo "<p>$valuesub</p>";
        }
    }
}

which works fine, but I think it's not the most efficient way since it's going through the second array for each item in the first... It doesn't seem right. 效果很好,但是我认为这不是最有效的方法,因为它要遍历第一个数组中的每个条目的第二个数组……这似乎不正确。

How to make it more efficient? 如何提高效率?

You can just use one for loop: 您可以只使用一个for循环:

for ($i = 0; $i < count($titlesArray); $i++) {
    echo "<h1>".$titlesArray[$i]."<h1>";
    echo "<p>".$paragraphsArray[$i]."</p>";
}

Use a sensible data structure: 使用合理的数据结构:

$content = array_map(null, $arrayone, $arraytwo);

foreach ($content as $entry) {
    printf('<h2>%s</h2>', $entry[0]);
    printf('<p>%s</p>', $entry[1]);
}

Or even: 甚至:

$content = array_combine($arrayone, $arraytwo);

foreach ($content as $title => $body) {
    printf('<h2>%s</h2>', $title);
    printf('<p>%s</p>', $body);
}

Assuming you've correctly set up the arrays to always have the same order and number of items: 假设您已经正确设置了数组,使其始终具有相同的顺序和数量:

for($i = 0; $i < count($arrayone); $i++) {
  echo "<h4>{$arrayone[$i]}</h4>";
  echo "<p>{$arraytwo[$i]}</p>";
}

You'd be better off with a more sensible array format, though: 不过,最好使用更合理的数组格式:

$array = [
  ['title' => 'Title one', 'content' => 'Content one'],
  ['title' => 'Title two', 'content' => 'Content two'],
];

Since all of the obvious answers have already been posted, here is just another way to do it 由于所有明显的答案都已发布,因此这是另一种方法

foreach (array_combine($arrayone, $arraytwo) as $title => $content) {
    printf('<h2>%s</h2><p>%s</p>', $title, $content);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM