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>";
        }
    }
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • dongtao1262 2018-11-05 15:24

    Try this:

    foreach ($carousel as $singleitem){
            echo "<cite>".$singleitem['cite']."</cite>
                  <blockquote>".$singleitem['blockquote']."</blockquote>";
            for ($i = 0; $i < $singleitem['imgs']; $i++) { //loop through img
                echo("image url" . "<br/>");
            }
        }
    
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题