简体   繁体   中英

How to sum values with same attribute in a multidimensional array?

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"
  }
}

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"];
} 

Assuming that $collection is the array of your objects

$sum5gal = 0;
$sum30gal = 0;
foreach ($collection as $obj){
    switch($obj->size){
        case "5 gal":
            $sum5gal++;
        break;
        case "30 gal":
            $sum30gal++;
        break;
    }
}

print "5 gal: " . $sum5gal . PHP_EOL;
print "30 gal: " . $sum30gal . PHP_EOL;

or

$sum = array(
    '5gal'  => $sum5gal,
    '30gal' => $sum30gal
)
print_r($sum);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM