从维数组计算相同的日期值

时间:2014-04-20 12:22:20

标签: php mysql sql arrays date

我有以下数组

$my_array = Array ( [0] => Array ( [date] => 2014-03-25 [total] => 649 ) [1] => Array ( [date] => 2014-03-29 [total] => 415.36 ) [2] => Array ( [date] => 2014-03-29 [total] => 29181.75 ) [3] => Array ( [date] => 2014-03-29 [total] => 1577.88 ) [4] => Array ( [date] => 2014-03-31 [total] => 849.4 ) [5] => Array ( [date] => 2014-04-11 [total] => 21382.2 ) [6] => Array ( [date] => 2014-04-16 [total] => 45022.5 ) )
在这样的foreach输出内部数组中的

$ my_array。

Array ( [date] => 2014-03-25 [total] => 649 )
Array ( [date] => 2014-03-29 [total] => 415.36 )
Array ( [date] => 2014-03-29 [total] => 29181.75 )
Array ( [date] => 2014-03-29 [total] => 1577.88 )
Array ( [date] => 2014-03-31 [total] => 849.4 )
Array ( [date] => 2014-04-11 [total] => 21382.2 )
Array ( [date] => 2014-04-16 [total] => 45022.5 )

日期29有3个销售,我试图获得每天应该输出的总销售额。

日期1总销售额 date2总销售额 日期3总销售额(如果总销售额为3)

有人可以帮我吗?

1 个答案:

答案 0 :(得分:0)

您可以使用array_walk并通过实施此回调函数来实现此目的。

<?php
$my_array = Array ( '0' => Array ( 'date' => '2014-03-25' ,'total' => 649 ), '1' => Array ( 'date' => '2014-03-29' ,'total' => 415.36 ), '2' => Array ( 'date' => '2014-03-29' ,'total' => 29181.75 ), '3' => Array ( 'date' => '2014-03-29', 'total' => 1577.88 ) ,'4' => Array ( 'date' => '2014-03-31', 'total' => 849.4 ), '5' => Array ( 'date' => '2014-04-11', 'total' => 21382.2 ) ,'6' => Array ( 'date' => '2014-04-16', 'total' => 45022.5 ) );
$new_arr = array();
array_walk($my_array,function ($v,$k) use(&$new_arr)
{
    array_key_exists($v['date'],$new_arr) ? $new_arr[$v['date']] = $new_arr[$v['date']]+$v['total'] : $new_arr[$v['date']]=$v['total'];
});
echo "<pre>";
print_r($new_arr);

<强> OUTPUT :

Array
(
    [2014-03-25] => 649
    [2014-03-29] => 31174.99
    [2014-03-31] => 849.4
    [2014-04-11] => 21382.2
    [2014-04-16] => 45022.5
)

如您所见,总销售额是值,日期是关键。总销售额已累加,并显示在每个日期旁边。