嵌套数组php中重复值的总和 [英] sum of duplicated values in nested array php
本文介绍了嵌套数组php中重复值的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个数组:
$data = Array
(
[1] => Array
(
[id] => '52040344'
[outcome] => 0
[names] => Array
(
[name_eng] => 'this is a name 2'
)
)
[2] => Array
(
[id] => 54030157
[outcome] => 1108541
[names] => Array
(
[name_eng] => 'this is a name 1'
)
)
[3] => Array
(
[id] => '54030157
[outcome] => '109635'
[names] => Array
(
[name_eng] => 'this is a name 1'
)
)
)
我想返回带有所有具有相同id的结果的总和,知道它们具有相同的id,它们就具有相同的名称。
i want to to return an array with the sum of all outcome having the same id, knowing that if they have same id, they have same name.
这样我就可以得到
array (
[0] => array( 'id' => '54030157', 'outcome' => 'sum of outcome', 'name' => 'this is name 1' ),
[1] => array( 'id' => '52040344', 'outcome' => 'sum of outcome', 'name' => 'this is name 2' )
)
我该怎么做??。
这是我所拥有的到目前为止已尝试过:
here is what i have tried so far :
public function process($data){
$outputArray = array();
foreach ($data as $key => $value) {
}
return $outputArray;
}
将不胜感激
推荐答案
编辑:在更新原始答案之前已获得答案!不注意某些特殊构造的输出数组,而只注意结果的计算。
Edit : Answered before update of original answer! Not taken notice of some special constructed output array, but only the calculation of outcome.
以下是您可以使用的一个小功能:
Here is a little function you can use :
function computeOutcome($array) {
$result=array();
foreach ($array as $item) {
$id=$item['id'];
if (isset($result[$id])) {
$result[$id]=$result[$id]+$item['outcome'];
} else {
$result[$id]=$item['outcome'];
}
}
return $result;
}
将多维数组作为参数传递。测试示例:
Pass your multidimensional array as parameter. Test example :
$test=array(
array('id'=>100, 'outcome'=>'45'),
array('id'=>200, 'outcome'=>'66'),
array('id'=>100, 'outcome'=>'88'),
array('id'=>200, 'outcome'=>'45')
);
print_r(computeOutcome($test));
输出
Array
(
[100] => 133
[200] => 111
)
这篇关于嵌套数组php中重复值的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文