首页 > 解决方案 > 从多维数组中取值

问题描述

我有一个多维数组:

$carousel = array(
    array(
        "cite" => 'title_1',
        "blockquote" => 'description_1',
        "imgs" => 4
    ),
        array(
        "cite" => 'title_2',
        "blockquote" => 'description_2',
        "imgs" => 2
    )
);

我想将此信息包装在 html 中并将 n 个图像作为 imgs 值回显。我只能回显 n 个图像,但我想分别关联引用和块引用。

我尝试使用 foreach 但没有成功:

foreach ($carousel as $images){
    foreach ($images as $key => $value){
        echo $value . "\n";
        for ($i = 0; $i < $value; $i++) {
            echo("image url" . "\n\n");
        }
    }
}

当我回显 $value 和图像时,我获得了所有值:

title_1
description_1
4
image url
image url
image url
image url

title_2
description_2
2
image url
image url

但我想像这样单独使用它们

<cite>title_1</cite>
<blockquote>description_1</blockquote>
<img></img> //4 times as specified in "imgs"
<img></img>
<img></img>
<img></img>

<cite>title_2</cite>
<blockquote>description_2</blockquote>
<img></img> //2 times as specified in "imgs"
<img></img>

我很感激任何建议。

标签: phparraysloopsmultidimensional-arrayforeach

解决方案


您有一个不需要的额外 foreach 循环。

尝试这个:

//loop through array
foreach($carousel as $values) {

    //echo cite info
    echo "<cite>{$values['cite']}</cite>";

    //echo blockquote info
    echo "<blockquote>{$values['blockquote']}</blockquote>";

    //loop until you have the same amount of <img> tags as defined in the `imgs` array element.
    for ($x = 1; $x <= $values['imgs']; $x++) {
        echo "<img></img>";
    }
}

推荐阅读