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

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

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

报告相同问题?