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

时间:2015-11-12 08:58:43

标签: php arrays

我有一个包含产品的数组,我想添加相同大小的产品总和。例如,在我的I阵列中,我有5个Gal和30个Gal尺寸。我想要总共5加尔和30加尔的总和(在我的阵列中5 Gal = 10和30 Gal = 9)。我太累了,无法弄清楚给我这个输出的方法......请帮忙。谢谢!

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 个答案:

答案 0 :(得分:0)

这很容易。使用foreach循环和总计数值如下:

play.http.router = app.Routes

如果你有更多的GAL尺寸,你可以尝试动态地进行:

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

答案 1 :(得分:0)

假设$collection是对象的数组

$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;

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