[英]PHP: Accumulate values in associative array
我想根据键的一部分在关联数组中累积值。
我测试了这个foreach循环,它在索引数组中工作正常:
$b = array();
foreach ($a as $key => $value) {
if ($key > 0) {
$b[$key] = $b[$key - 1] + $value;
}
}
我无法让它在关联数组中工作,但......
$a
(摘录)
Array (
[2014-04-22|Paul] => 0
[2014-04-28|Paul] => 2
[2014-05-13|Paul] => 0
[2014-06-03|Paul] => 1
[2014-06-12|Paul] => 0
[2014-08-11|Paul] => 1
[2014-08-28|Paul] => 3
[2012-05-09|John] => 1
[2012-08-29|John] => 2
[2012-09-05|John] => 0
[2012-09-13|John] => 1
)
$b
(期望的结果)
Array (
[2014-04-22|Paul] => 0
[2014-04-28|Paul] => 2
[2014-05-13|Paul] => 2
[2014-06-03|Paul] => 3
[2014-06-12|Paul] => 3
[2014-08-11|Paul] => 4
[2014-08-28|Paul] => 7
[2012-05-09|John] => 1
[2012-08-29|John] => 3
[2012-09-05|John] => 3
[2012-09-13|John] => 4
)
在期望的结果中,每个值是“保罗”和“约翰”(以及更多)累积到前一个值。
通过使用array_walk ,检查当前名称是否与下一个名称相同,因为我正在通过next重置值。
$result = [];
$tempKey = '';
$arr = array_walk($arr, function($item, $key) use(&$result, &$tempKey, &$total){
list($date, $name) = explode("|", $key); // explode key
if(empty($tempKey) || $tempKey != $name){ // if empty or if conflict
$tempKey = $name; // tempKey for reference
$total = $item; // total reset to current value
}else{
$total += $item; // adding for same name
}
$result[$key] = $total; // putting calculated value
});
print_r($result);
产量
Array
(
[2014-04-22|Paul] => 0
[2014-04-28|Paul] => 2
[2014-05-13|Paul] => 2
[2014-06-03|Paul] => 3
[2014-06-12|Paul] => 3
[2014-08-11|Paul] => 4
[2014-08-28|Paul] => 7
[2012-05-09|John] => 1
[2012-08-29|John] => 3
[2012-09-05|John] => 3
[2012-09-13|John] => 4
)
演示 。
您可以通过跟踪密钥的名称部分以及在获得新名称时重置总计数来执行此操作:
$b = array();
$lastname = '';
foreach ($a as $key => $value) {
list($d, $n) = explode('|', $key);
if ($n == $lastname) {
$total += $value;
}
else {
$total = $value;
}
$b[$key] = $total;
$lastname = $n;
}
print_r($b);
输出:
Array (
[2014-04-22|Paul] => 0
[2014-04-28|Paul] => 2
[2014-05-13|Paul] => 2
[2014-06-03|Paul] => 3
[2014-06-12|Paul] => 3
[2014-08-11|Paul] => 4
[2014-08-28|Paul] => 7
[2012-05-09|John] => 1
[2012-08-29|John] => 3
[2012-09-05|John] => 3
[2012-09-13|John] => 4
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.