PHP数组 - 同样关键的总和值时,关键是数量
我的情况是类似这样的主题:
My situation is similar to this thread :
Associative阵列,同样关键的和值
然而,在我的情况下,所有键数量。
我想,以减少/联合数组,其中0键是类似的,使所有其他按键的总和。
However in my case all keys are number. I would like to reduce / combine array where key 0 is similar and make a sum of all other keys.
下面是我原来的数组:
Array
(
[0] => Array
(
[0] => 093042
[1] => 3
[2] => 0
[4] => 0
)
[1] => Array
(
[0] => 222032
[1] => 0
[2] => 13
[4] => 0
)
[2] => Array
(
[0] => 222032
[1] => 0
[2] => 0
[4] => 15
)
[3] => Array
(
[0] => 152963
[1] => 45
[2] => 0
[4] => 0
)
[4] => Array
(
[0] => 222032
[1] => 0
[2] => 7
[4] => 0
)
)
和这里的输出我需要:
Array
(
[0] => Array
(
[0] => 093042
[1] => 3
[2] => 0
[4] => 0
)
[1] => Array
(
[0] => 222032
[1] => 0
[2] => 20
[4] => 15
)
[2] => Array
(
[0] => 152963
[1] => 45
[2] => 0
[4] => 0
)
)
其他线程的解决办法是行不通的,因为他们使用的键名,我不知道我这怎么能适应我的情况。
The solution of other thread is not working because they use the key name and i don't know how i can adapt this to my situation.
请,如果你能给我工作液的例子。
Please if you can give me an example of working solution.
REPLY:
现在我尝试类似的东西:从其他线程以
For now i try something like that : Take from other thread
$sum = array_reduce($data, function ($a, $b) {
if (isset($a[$b[0]])) {
$a[$b[0]]['budget'] += $b['budget'];
}
else {
$a[$b[0]] = $b;
}
return $a;
});
但这个例子看起来是只为一个名为关键的预算,但在我的情况是一些和我有3个关键[1] [2] [3]怎么能不总结键1,2,4,其中0键类似于
But this example look is only for key named budget but in my case is number and i have 3 key [1] [2] [3] how can't sum key 1,2,4 where key 0 is similar
这应该为你工作:
基本上我只是通过您的数组循环,并检查是否已存在于 $结果元素
与 $ V的第一个元素的关键
。如果不是我与 array_pad初始化()
编辑阵列0 +当前foreach循环迭代数组的。
Basically I just loop through your array and check if there is already an element in $result
with the key of the first element of $v
. If not I initialize it with an array_pad()
'ed array of 0's + the current array of the iteration of the foreach loop.
并通过 $ V
预计第一个并把它添加到结果数组中的每个元素这个我循环之后
And after this I loop through each element of $v
expect the first one and add it to the result array.
最后我只是重新索引与结果数组array_values()
。
At the end I just reindex the result array with array_values()
.
<?php
foreach($arr as $v){
if(!isset($result[$v[0]]))
$result[$v[0]] = array_pad([$v[0]], count($v), 0);
$count = count($v);
for($i = 1; $i < $count; $i++)
$result[$v[0]][$i] += $v[$i];
}
$result = array_values($result);
print_r($result);
?>
输出:
Array
(
[0] => Array
(
[0] => 093042
[1] => 3
[2] => 0
[3] => 0
)
[1] => Array
(
[0] => 222032
[1] => 0
[2] => 20
[3] => 15
)
[2] => Array
(
[0] => 152963
[1] => 45
[2] => 0
[3] => 0
)
)