douhushen3241 2018-11-05 15:16
浏览 46
已采纳

从多维数组中获取值

I have a multidimensional array:

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

I want to wrap this infos in html and echo n images as the imgs value. I only be able to echo n images but i want to associate cites and blockquotes separately.

I tried to use foreach but with no success:

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

");
        }
    }
}

I obtain all the values when I echo $value and images:

title_1
description_1
4
image url
image url
image url
image url

title_2
description_2
2
image url
image url

but I want to use them separately like this

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

I appreciate any suggestion.

  • 写回答

2条回答 默认 最新

  • dsgawmla208057 2018-11-05 15:23
    关注

    You have an extra foreach loop that you do not need.

    Try this:

    //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>";
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?