[英]How to sum value of array if some values are same?
I have following array 我有以下数组
Array (
[0] => 1995,17500
[1] => 2052,17500
[2] => 2052,17500
[3] => 2236,30000
[4] => 2235,15000
[5] => 2235,40000
);
I have exploded the value with comma ,. 我已经用逗号将值分解了。
foreach($array as $key=>$value) {
$newar = explode(',', $value);
}
So I have similar first value ie $newar["0"]. 所以我有相似的第一个值,即$ newar [“ 0”]。 For example 2235 and 2052. And I would like to have sum of second value ie $newar["1"].
例如2235和2052。并且我想要第二个值的总和,即$ newar [“ 1”]。
How can I achieve following result with PHP. 如何使用PHP实现以下结果。
Array (
[0] => 1995, 17500
[1] => 2052, 35000
[2] => 2036, 30000
[3] => 2235, 55000
)
You can create a new array key/index based and use array_key_exists
to check if the key already exists. 您可以创建一个新的基于数组键/索引的数组,并使用
array_key_exists
检查该键是否已存在。 If so sum the value, if not create the key. 如果是这样,则求和该值,否则请创建密钥。 This is not the exact result you want, but it's neater.
这不是您想要的确切结果,但是更整洁。
$newar = []; //New Array
foreach($array as $value) {
$explArr = explode(',', $value);
if(array_key_exists($explArr[0], $newar)){ //Check if the key already exists
$newar[$explArr[0]] += $explArr[1]; //Sum value to existing key
} else {
$newar[$explArr[0]] = $explArr[1]; //Create key
}
}
Your result array will look like this: 您的结果数组将如下所示:
Array (
[1995] => 17500
[2052] => 35000
[2036] => 30000
[2235] => 55000
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.