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 目详情-五一模拟赛详情页
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line