drus40229 2013-12-05 22:56
浏览 16
已采纳

按相同的模型和条件计算foreach循环

I would like to get the count (total) of values in my foreach loop which share the same 'Model' and 'Condtion'.

To help you understand better, here is a representation of how my data looks like

 Product Name            |    Condition
 ---------------------------------------
 iPhone 3G 16GB          |    Used

 iPhone 3G 16GB          |    Used

 iPhone 3G 16GB          |    New

 Blackberry 9900         |    New

 Blackberry 9900         |    New

My current foreach loop:-

 $results = getProducts();

 foreach ($results as $result) {

 $data[] = array (
'model' => $result['model'],
'condition' => $result['condition']
 );  
}

This is what I get with my current foreach loop:-

 Array (

[0] => Array
    (
        [model] => iPhone 3G 16GB
        [condition] => Used
    )

[1] => Array
    (
        [model] => iPhone 3G 16GB
        [condition] => Used
    )

[2] => Array
    (
        [model] => iPhone 3G 16GB
        [condition] => New
    )
[3] => Array
    (
        [model] => Blackberry 9900
        [condition] => New
    )
[4] => Array
    (
        [model] => Blackberry 9900
        [condition] => New
    )
)

Here is how and what I would like to get instead:-

 Array(
 'Apple iPhone 3G 16GB' => Array (
 'Used' => 2,
 'New' => 1
 )
 'Blackberry 9900' => Array (
 'New' => 2 
 )
)

Hope you get an idea of what I'm trying to accomplish here. Please let me know if you would like me to provide any additional info.

  • 写回答

2条回答 默认 最新

  • douchen9569 2013-12-05 23:00
    关注

    This should give you the desired result.

    $data = array();
    foreach ($results as $result) {
        if (!array_key_exists($result['model'], $data)) {
            $data[ $result['model'] ] = array(
                'Used' => 0,
                'New' => 0
            );
        }
        $data[ $result['model'] ][ $result['condition'] ]++;
    }
    

    Keep in mind that alphabetical indices are case sensitive in PHP, so you might want to add a strtolower() to avoid undefined index notices.

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

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?