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

报告相同问题?

悬赏问题

  • ¥15 labview程序设计
  • ¥15 为什么在配置Linux系统的时候执行脚本总是出现E: Failed to fetch http:L/cn.archive.ubuntu.com
  • ¥15 Cloudreve保存用户组存储空间大小时报错
  • ¥15 伪标签为什么不能作为弱监督语义分割的结果?
  • ¥15 编一个判断一个区间范围内的数字的个位数的立方和是否等于其本身的程序在输入第1组数据后卡住了(语言-c语言)
  • ¥15 游戏盾如何溯源服务器真实ip?
  • ¥15 Mac版Fiddler Everywhere4.0.1提示强制更新
  • ¥15 android 集成sentry上报时报错。
  • ¥50 win10链接MySQL
  • ¥15 抖音看过的视频,缓存在哪个文件