综上所述,而preserving键名多维关联数组值 [英] Sum multidimensional associative array values while preserving key names
问题描述
有很多不错的Q&安培;#2一如何采取在其多维关联数组和和值。不幸的是,我无法找到一个地方键名的不是丢失。
例如:
$ ARR =阵列(
阵列(ID= GT;'1','量'=>'5'),
阵列(ID= GT;'1','量'=>'5'),
阵列('ID'=>'2','量'=>'1'),
阵列(ID= GT;'2','量'=>'3')
);
我想要的结果数组看起来像这样:
$结果=阵列(
阵列(ID= GT;'1','量'=> '10'),
阵列(ID= GT;'2','量'=>'4')
);
不幸的是,我可以弄清楚如何做的唯一事情是这样的:
$结果=阵列();
的foreach($改编为$金额){
如果(!array_key_exists($量['身份证'],$ ARR))
$结果[$量['身份证'] = 0;
$结果[$量['身份证'] + = $量['量'];
}
,当回显的
如下产生(注意缺少的钥匙的话id和量):
的foreach($结果作为的$ id => $金额){
回声$ id为==>中。$量\\ n。
}1 ==→10
2 ==→4
为什么不使用这种方法,然后重建在最后要在阵列?
$结果=阵列();
的foreach($改编为的$ id => $金额){
$结果[] =阵列('ID'=>的$ id,'量'=> $金额);
}
这样做的任何其他方式将更加计算昂贵的。
There are many nice Q&A on Stackoverflow on how to take a multidimensional associative array and sum values in it. Unfortunately, I can't find one where the key names aren't lost.
For example:
$arr=array(
array('id'=>'1', 'amount'=>'5'),
array('id'=>'1', 'amount'=>'5'),
array('id'=>'2', 'amount'=>'1'),
array('id'=>'2', 'amount'=>'3')
);
I want the resulting array to look like this:
$result=array(
array('id'=>'1', 'amount'=>'10'),
array('id'=>'2', 'amount'=>'4')
);
Unfortunately the only thing I can figure out how to do is this:
$result = array();
foreach($arr as $amount){
if(!array_key_exists($amount['id'], $arr))
$result[$amount['id']] =0;
$result[$amount['id']] += $amount['amount'];
}
Which when echo'd
as follows produces (notice the lack of the keys' words "id" and "amount"):
foreach($result as $id => $amount){
echo $id."==>".$amount."\n";
}
1==>10
2==>4
Why not use that method, and then reconstruct the array you want at the end?
$results = array();
foreach ($arr as $id=>$amount) {
$results[] = array('id' => $id, 'amount' => $amount);
}
Any other way of doing this would be more computationally expensive.
这篇关于综上所述,而preserving键名多维关联数组值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!