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

报告相同问题?

悬赏问题

  • ¥60 pb数据库修改或者求完整pb库存系统,需为pb自带数据库
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路