douyan1972 2013-03-05 00:22
浏览 55
已采纳

嵌套的foreach循环

I have an array that looks like this

$foreacharray = array(
    "model" => array ("samsung", "sony", "philips", "acer", "hp"),
    "qty" => array("3", "7", "5", "1", "8"),
);

What I'm trying to do is foreach model, draw the logo for the amount of its qty so Samsung = 3, Sony = 7 and so on will draw 3 Sony logos and 7 Samsung logos.

I came up with something like this

foreach ($foreacharray["model"] as $model)
{
    foreach($foreacharray["qty"] as $qty)
    {
        echo $model;
        echo '<br>';
    }
}

But of course all that does is for each of the array entries, echo out the name so I end up with 5 samsungs being printed 5 sonys being printed etc.

How can I make this use the value of the qty array rather than the number of entries?

  • 写回答

7条回答 默认 最新

  • douyouming9180 2013-03-05 00:30
    关注

    Why not make this simpler by using the function array_combine?

    http://www.php.net/manual/en/function.array-combine.php

    Example;

    $newArray = array_combine($foreacharray[0], $foreacharray[1]);
    var_dump($newArray);
    // will output
    array (
         "samsung" => 3,
         "sony" => 7,
         "philips" => 5,
         "acer" => 1, 
         "hp" => 8,
    )
    

    Then you can easily get all values or display them like so...

    foreach($newArray as $key => $val) {
        echo $key . ' has a quantity of ' . $val . '.';
    }
    

    Hope this makes it easier.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(6条)

报告相同问题?

悬赏问题

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