我这样排列,现在我想对具有相同发起人名称的费用进行总计。
并使用该数组创建一个新数组,因此这里有3个cima haves,我需要其中的一个数组,其中fee_potetial
是发起者为cima haves的所有其他数组的总和。
$formEntries
返回如下值:
Array
(
[0] => Array
(
[entry_id] => 54
[0] => 1
[fee_potential] => 100
[originator] => cima haves
)
[1] => Array
(
[entry_id] => 55
[0] => 1
[fee_potential] => 600
[originator] => steve
)
[2] => Array
(
[entry_id] => 56
[0] => 1
[fee_potential] => 500
[originator] => cima haves
)
[3] => Array
(
[entry_id] => 57
[0] => 1
[fee_potential] => 500
[originator] => cima haves
)
)
这是我尝试隔离的代码:
$originator = array_column($formEntries, 'originator');
$originator = array_unique($originator);
$array_filter = array_filter($formEntries, function ($key, $value) use ($originator) {
return in_array($value, array_keys($originator));
}, ARRAY_FILTER_USE_BOTH);
我需要输出[fee_potential] => 1100是总和
Array
(
[0] => Array
(
[entry_id] => 54
[0] => 1
[fee_potential] => 1100
[originator] => cima haves
)
[1] => Array
(
[entry_id] => 55
[0] => 1
[fee_potential] => 600
[originator] => steve
)
)
答案 0 :(得分:2)
一个简单的foreach循环会非常简单
$totals = [];
foreach( $formEntries as $entry) {
if( isset($totals[$entry['originator']]){
$totals[$entry['originator']]['fee_potential'] += $entry['fee_potential'];
} else {
$totals[$entry['originator']]['fee_potential'] = $entry['fee_potential'];
}
}
答案 1 :(得分:2)
只需尝试遍历所有此类元素
$final_arr = array();
foreach($formEntries as $value){
if(isset($final_arr[$value['originator']])){
$final_arr[$value['originator']]['fee_potential'] += $value['fee_potential'];
}
else{
$final_arr[$value['originator']] = $value;
}
}
它将检查最终数组中是否已存在originator
。如果是这样,它将对值求和,否则它将与fee_potential
一起分配该数组。
答案 2 :(得分:0)
尝试使用此代码,即可正常运行。
$result = array();
foreach($formEntries as $key => $v){
if(in_array($v['originator'], array_column($result, 'originator'))){
$result[array_search($v['originator'], array_column($result, 'originator'))]['fee_potential'] += $v['fee_potential'];
}else{
$result[$key] = $v;
}
}
结果:-
Array
(
[0] => Array
(
[entry_id] => 54
[0] => 1
[fee_potential] => 1100
[originator] => cima haves
)
[1] => Array
(
[entry_id] => 55
[0] => 1
[fee_potential] => 600
[originator] => steve
)
)