[英]PHP 2d array sum on same index value
So I have 2d array, with some arrays inside. 所以我有2d数组,里面有一些数组。 indexes are all same in arrays: "id" and "cost". 索引在数组中都相同:“ id”和“ cost”。 On same "id" values I want to sum "number" values. 在相同的“ id”值上,我想对“ number”值求和。 Here's my 2d array: 这是我的二维数组:
$array = array (
array ('id' => 2, 'cost' => 300),
array ('id' => 1, 'cost' => 200),
array ('id' => 2, 'cost' => 100),
);
I've made some code, but it get's not exactly what i want. 我已经编写了一些代码,但是它并不是我想要的。
$result = array ();
foreach($array as $item){
if (isset($result[$item['id']])){
$result[$item['id']] += $item['cost'];
}else{
$result[$item['id']] = $item['cost'];
}
}
var_dump($result);
Will show me this: 会告诉我这个:
array (size=2)
2 => int 400
1 => int 200
I want it to show me like this: 我希望它向我显示这样的内容:
array (size=2)
0 =>
array (size=2)
'id' => int 2
'cost' => int 400
1 =>
array (size=2)
'id' => int 1
'cost' => int 200
Any help would be perfect :) 任何帮助将是完美的:)
You can initiate it as an array if the key does not exist. 如果键不存在,则可以将其启动为数组。 Add the cost
if it already exist. 如果已经存在,则添加cost
。
$array = array (
array ('id' => 2, 'cost' => 300),
array ('id' => 1, 'cost' => 200),
array ('id' => 2, 'cost' => 100),
);
$result = array ();
foreach($array as $item){
if (isset($result[$item['id']])){
//Add the cost
$result[$item['id']]["cost"] += $item['cost'];
} else {
//Init as array
$result[$item['id']] = array( "id" => $item['id'], "cost" => $item['cost'] );
}
}
This will result to: 这将导致:
Array
(
[2] => Array
(
[id] => 2
[cost] => 400
)
[1] => Array
(
[id] => 1
[cost] => 200
)
)
You can use foreach
and array_values
for the desired result 您可以使用foreach
和array_values
获得所需的结果
$array = array (
array ('id' => 2, 'cost' => 300),
array ('id' => 1, 'cost' => 200),
array ('id' => 2, 'cost' => 100),
);
$res = [];
foreach($array as $key => $value){
array_key_exists($value['id'], $res) ? (
$res[$value['id']]['cost'] += $value['cost']
)
:
(
$res[$value['id']] = [
'id' => $value['id'],
'cost' => $value['cost']
]
);
}
echo '<pre>';
print_r(array_values($res));
Result 结果
Array
(
[0] => Array
(
[id] => 2
[cost] => 400
)
[1] => Array
(
[id] => 1
[cost] => 200
)
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.