dongpi3237 2015-11-12 08:58
浏览 66
已采纳

如何在多维数组中对具有相同属性的值求和?

I have an array with products, and I want to add the sum of the products with same size. For example in my I array I have 5 Gal and 30 Gal sizes. I want the sum of total 5 Gals and 30 gals( in my array 5 Gal = 10 and 30 Gal = 9). I am too tired to figure out the method to give me this output...please help. Thanks!

array(7) {
  [0]=>
  object(stdClass)#223 (9) {
    ["size"]=>
    string(6) "30 GAL"
    ["list_price"]=>
    string(3) "614"
    ["count"]=>
    string(1) "2"
  }
  [1]=>
  object(stdClass)#224 (9) {
    ["size"]=>
    string(5) "5 Gal"
    ["list_price"]=>
    string(3) "131"
    ["count"]=>
    string(1) "3"
  }
  [2]=>
  object(stdClass)#225 (9) {
    ["size"]=>
    string(6) "30 GAL"
    ["list_price"]=>
    string(3) "727"
    ["count"]=>
    string(1) "4"
  }
  [3]=>
  object(stdClass)#226 (9) {
    ["size"]=>
    string(5) "5 Gal"
    ["list_price"]=>
    string(3) "138"
    ["count"]=>
    string(1) "1"
  }
  [4]=>
  object(stdClass)#227 (9) {
    ["size"]=>
    string(6) "30 GAL"
    ["list_price"]=>
    string(3) "804"
    ["count"]=>
    string(1) "3"
  }
  [5]=>
  object(stdClass)#228 (9) {
    ["size"]=>
    string(5) "5 Gal"
    ["list_price"]=>
    string(3) "176"
    ["count"]=>
    string(1) "4"
  }
  [6]=>
  object(stdClass)#229 (9) {
    ["size"]=>
    string(5) "5 Gal"
    ["list_price"]=>
    string(3) "182"
    ["count"]=>
    string(1) "2"
  }
}
  • 写回答

2条回答 默认 最新

  • dongshenling6585 2015-11-12 09:05
    关注

    It's quite easy. Use foreach loop and sum count values as follow:

    $count5GAL = 0;
    $count30GAL = 0;
    
    foreach($array as $value) {
        if ($value["size"] == "5 Gal") $count5GAL += $value["count"];
        else if ($value["size"] == "30 Gal") $count30GAL += $value["count"];
    }
    

    If you have more GAL sizes you could try to do it dynamically:

    $counter = array();
    
    foreach($array as $value) {
        $keyName = str_replace(' ','',$value["size"]);
        if (!array_key_exists($counter,$keyName) array[$keyName] = $value["count"];
        else array[$keyName] += $value["count"];
    } 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 求数学坐标画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站