PHP自定义数组基于相同值和值总和合并 [英] PHP custom array merge on bases of same value and sum of value
问题描述
Array(
[0] => Array(
[account] => 251234567890,
[price] => 83
) [1] => Array(
[account] => 251234567890,
[price] => 27
) [2] => Array(
[account] => 251234564526,
[price] => 180
) [3] => Array(
[account] => 251234567890,
[price] => 40
)
)
现在我想合并具有相同帐户
的数组,并且其总和特别是 price
。
now with i want to merge array with same account
and sum of it's particular price
.
Array(
[251234567890] => Array(
[account] => 251234567890,
[price] => 150
) [251234564526] => Array(
[account] => 251234564526,
[price] => 180
)
)
我有
I have tried like this,
$res = array();
$k = 0;
foreach ($to_account as $vals) {
if (array_key_exists($vals['account'], $res)) {
$res[$k]['price'] += $vals['price'];
$res[$k]['account'] = $vals['account'];
$k++;
} else {
$res[$k] = $vals;
$k++;
}
}
如在输入数组中所示仅存在两个唯一的帐户
,因此输出数组应该是两个帐户的价格之和
As here in input array only two unique account
is present so output array should be of that two account with sum of it's price
我在 php
中使用它,希望有人可以在此帮助我
I have seen something like this in python
from here but it want be helpful as it is in python i want it in php
i hope someone can help me in this
谢谢
推荐答案
通过分配临时密钥,您可以确定是否要处理第一次出现的密钥,然后使用适当的技术来存储整个密钥子数组或仅向子数组的 price
元素添加值。
By assigning temporary keys, you can determine whether you are dealing with the first occurrence or not and then use the appropriate technique to either store the whole subarray or merely add value to the price
element of the subarray.
代码:(演示)
$to_account = [
[ 'account' => 251234567890, 'price' => 83 ],
[ 'account' => 251234567890, 'price' => 27 ],
[ 'account' => 251234564526, 'price' => 180 ],
[ 'account' => 251234567890, 'price' => 40 ]
];
foreach ($to_account as $row) {
if (!isset($result[$row['account']])) {
$result[$row['account']] = $row;
} else {
$result[$row['account']]['price'] += $row['price'];
}
}
var_export($result);
输出:
array (
251234567890 =>
array (
'account' => 251234567890,
'price' => 150,
),
251234564526 =>
array (
'account' => 251234564526,
'price' => 180,
),
)
这篇关于PHP自定义数组基于相同值和值总和合并的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!