按日期分组php数组 [英] Group php array by date

查看:229
本文介绍了按日期分组php数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组:

Array
(
    [0] => Array
        (
            [id] => 81
            [placed] => 2013-09-19 16:32:53
            [sub_total] => 786
        )

    [1] => Array
        (
            [id] => 80
            [placed] => 2013-09-19 16:32:06
            [sub_total] => 780
        )

    [2] => Array
        (
            [id] => 79
            [placed] => 2013-09-18 17:06:48
            [sub_total] => 786
        )

    [3] => Array
        (
            [id] => 78            
            [placed] => 2013-09-18 17:05:02
            [sub_total] => 756
        )

    [4] => Array
        (
            [id] => 77          
            [placed] => 2013-09-17 17:02:53
            [sub_total] => 786
        )

    [5] => Array
        (
            [id] => 76
            [placed] => 2013-09-16 17:02:53
            [sub_total] => 756
        )
)

是否可以按日期对数据进行分组并汇总小计以获得输出数组:

Is it possible to group this data by date and summarize subtotal amount to get output array:

 Array
    (
        [0] => Array
            (
                [placed] => 2013-09-19
                [sub_total] => 786 + 780
            )

        [2] => Array
            (
                [placed] => 2013-09-18
                [sub_total] => 786 + 756
            )

        [3] => Array
            (
                [placed] => 2013-09-17 17:02:53
                [sub_total] => 786
            )

        [4] => Array
            (
                [placed] => 2013-09-16 17:02:53
                [sub_total] => 756
            )
    )


推荐答案

我也对此进行了测试: http://phpfiddle.org/main/code/rzv-ngp

I tested this also: http://phpfiddle.org/main/code/rzv-ngp

<?php
Array
(
    '0' => Array
        (
            'id' => '81',
            'placed' => '2013-09-19 16:32:53',
            'sub_total' => '786'
        ),

    '1' => Array
        (
            'id' => '80',
            'placed' => '2013-09-19 16:32:06',
            'sub_total' => '780'
        ),

//...
);

$newarray = array();
foreach ($array as $value){
 $temp = explode(" ", $value['placed']);
 $date = $temp[0];
    $total = (isset($newarray[$date]['sub_total']) ? $newarray[$date]['sub_total'] + $value['sub_total']: $value['sub_total']);
 $newarray[$date] = array('placed' => $date, 'sub_total' => $total);
}

print_r($newarray);

?>

这篇关于按日期分组php数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆