我有一个数组:
Array
(
[2015-09-23] => Array
(
[user] => Array
(
[0] => 13
[1] => 12
)
[count] => Array
(
[count] => 2
[total] => 2
)
)
[2015-09-24] => Array
(
[user] => Array
(
[0] => 14
)
[count] => Array
(
[count] => 1
[total] => 1
)
)
[2015-09-25] => Array
(
[user] => Array
(
[0] => 15
)
[count] => Array
(
[count] => 1
[total] => 1
)
)
[2015-09-26] => Array
(
[user] => Array
(
[0] => 16
)
[count] => Array
(
[count] => 1
[total] => 1
)
)
[2015-09-27] => Array
(
[user] => Array
(
[0] => 17
[1] => 18
)
[count] => Array
(
[count] => 2
[total] => 2
)
)
[2015-09-28] => Array
(
[user] => Array
(
[0] => 19
[1] => 20
[2] => 21
[3] => 22
[4] => 23
[5] => 24
[6] => 25
[7] => 26
[8] => 27
[9] => 28
)
[count] => Array
(
[count] => 10
[total] => 10
)
)
)
我的愿景是通过前一个元素的值增加每个值count ['count']。例如,如果前一个值是2,当前值是2,那么总数将是4.如果下一个值是1,那么它将是5.我根本不知道如何制作它......这就是我之前所拥有的现在
$arr_keys = array_keys($this->tmp_data['month_users_formatted']);
foreach ( array_keys($arr_keys) as $key ) {
$this_value = $this->tmp_data['month_users_formatted'][$arr_keys[$key]];
if ( isset($this->tmp_data['month_users_formatted'][$arr_keys[$key - 1]]) ){
$prev_value = $this->tmp_data['month_users_formatted'][$arr_keys[$key - 1]];
$this_value['count']['total'] = $this_value['count']['total'] + $prev_value['count']['total'];
}
}
这就是最后的样子:
Array
(
[2015-09-23] => Array
(
[user] => Array
(
[0] => 13
[1] => 12
)
[count] => Array
(
[count] => 2
[total] => 2
)
)
[2015-09-24] => Array
(
[user] => Array
(
[0] => 14
)
[count] => Array
(
[count] => 1
[total] => 3
)
)
[2015-09-25] => Array
(
[user] => Array
(
[0] => 15
)
[count] => Array
(
[count] => 1
[total] => 4
)
)
[2015-09-26] => Array
(
[user] => Array
(
[0] => 16
)
[count] => Array
(
[count] => 1
[total] => 5
)
)
[2015-09-27] => Array
(
[user] => Array
(
[0] => 17
[1] => 18
)
[count] => Array
(
[count] => 2
[total] => 7
)
)
[2015-09-28] => Array
(
[user] => Array
(
[0] => 19
[1] => 20
[2] => 21
[3] => 22
[4] => 23
[5] => 24
[6] => 25
[7] => 26
[8] => 27
[9] => 28
)
[count] => Array
(
[count] => 10
[total] => 17
)
)
)
答案 0 :(得分:1)
$total = 0;
foreach($countsAndTotals as $key => $countAndTotal) {
$total += $countAndTotal['count']['count'];
$countsAndTotals[$key]['count']['total'] = $total;
}
print_r($countsAndTotals);
这将获取数组并将所有计数值相加,然后用$ total变量替换总值。
答案 1 :(得分:0)
您可以使用foreach并通过引用设置var:
$muf = $this->tmp_data['month_users_formatted'];
$total = 0;
foreach($muf as &$month){
$month['count']['total']+=$total;
$total+= $month['count']['total'];
}