对于给定的场景,我无法找到解决方案,因为我有一个多维数组,必须在其中找到具有相同ID的数组的值之和。
demo.php
$array = array("1"=>array("id"=>"1", "total"=>"100"),
"2"=>array("id"=>"2", "total"=>"300"),
"3"=>array("id"=>"3", "total"=>"400"),
"4"=>array("id"=>"4", "total"=>"500"),
"5"=>array("id"=>"1", "total"=>"560"));
我想获取所有重复ID的总数,例如1是该ID,总数为100 + 560 = 650。
答案 0 :(得分:2)
一种选择是使用array_reduce
将数组汇总为一个关联数组。
$array = //....
$result = array_reduce( $array, function( $c, $v ){
if ( !isset( $c[ $v["id"] ] ) ) $c[ $v["id"] ] = 0;
$c[ $v["id"] ] += $v["total"];
return $c;
}, array() );
$result
将是:
Array
(
[1] => 660
[2] => 300
[3] => 400
[4] => 500
)
更新
添加另一个reduce
以首先对数组进行分组。第二个reduce
仅包含具有多个计数的数组元素。
$array = //....
$group = array_reduce( $array, function( $c, $v ){
if ( !isset( $c[ $v["id"] ] ) ) $c[ $v["id"] ] = [ "count" => 0, "total" => 0, "id" => $v["id"] ];
$c[ $v["id"] ]["count"] += 1;
$c[ $v["id"] ]["total"] += $v["total"];
return $c;
}, array() );
$result = array_reduce( $group, function( $c, $v ){
if ( $v["count"] > 1 ) $c[ $v["id"] ] = $v["total"];
return $c;
}, array() );
这将导致:
Array
(
[1] => 660
)
答案 1 :(得分:2)
使用foreach
时的另一种方法:
$array = array("1"=>array("id"=>"1", "total"=>"100"),
"2"=>array("id"=>"2", "total"=>"300"),
"3"=>array("id"=>"3", "total"=>"400"),
"4"=>array("id"=>"4", "total"=>"500"),
"5"=>array("id"=>"1", "total"=>"560"));
$total = [];
foreach ($array as $sub) {
$total[$sub['id']] = isset($total[$sub['id']]) ? $total[$sub['id']] += $sub['total'] : $total[$sub['id']] = $sub['total'];
}
输出
Array
(
[1] => 660
[2] => 300
[3] => 400
[4] => 500
)
实时示例
阅读材料
答案 2 :(得分:1)
您可以使用简单的foreach循环来获得预期的结果
<?php
// Your code here!
$array = array("1"=>array("id"=>"1", "total"=>"100"),
"2"=>array("id"=>"2", "total"=>"300"),
"3"=>array("id"=>"3", "total"=>"400"),
"4"=>array("id"=>"4", "total"=>"500"),
"5"=>array("id"=>"1", "total"=>"560"));
$issetArray = array();
foreach ($array as $key => $value) {
if(isset($issetArray[$value['id']]))
{
$issetArray[$value['id']]['total'] += $value['total'];
}
else
{
$issetArray[$value['id']] = array();
$issetArray[$value['id']] = $value;
}
}
$result = array();
foreach ($issetArray as $value) {
array_push($result, $value);
}
print_r($result);
?>
答案 3 :(得分:0)
如果您要使用外部类tableArray,并且想要保留输入数组的结构,请尝试以下操作:
$array = array("1"=>array("id"=>"1", "total"=>"100"),
"2"=>array("id"=>"2", "total"=>"300"),
"3"=>array("id"=>"3", "total"=>"400"),
"4"=>array("id"=>"4", "total"=>"500"),
"5"=>array("id"=>"1", "total"=>"560"));
$newData = tableArray::create($array)
->filterGroupSum('total',['id'])
->fetchAll()
;
$ newData:
array (
0 =>
array (
'id' => "1",
'total' => 660,
),
1 =>
array (
'id' => "2",
'total' => 300,
),
2 =>
array (
'id' => "3",
'total' => 400,
),
3 =>
array (
'id' => "4",
'total' => 500,
),
)