如何按日期分组此PHP数组并求和 [英] How to group this PHP array by date and sum the values

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

问题描述

我有这个PHP数组-我需要按日期分组,我假设是通过创建另一个数组,然后将每个日期的成人人数相加

I have this PHP array - I need to group by date, I am assuming by creating another array, and add up the number of adults for each date

Array
(
[0] => stdClass Object
    (
        [thedate] => 2016-04-09
        [theadults] => 5
    )

[1] => stdClass Object
    (
        [thedate] => 2016-04-09
        [theadults] => 8
    )

[2] => stdClass Object
    (
        [thedate] => 2016-04-09
        [theadults] => 12
    )

[3] => stdClass Object
    (
        [thedate] => 2016-03-05
        [theadults] => 1
    )

[4] => stdClass Object
    (
        [thedate] => 2016-02-27
        [theadults] => 1
    )

[5] => stdClass Object
    (
        [thedate] => 2016-03-05
        [theadults] => 1
    )

[6] => stdClass Object
    (
        [thedate] => 2016-03-05
        [theadults] => 1
    )

[7] => stdClass Object
    (
        [thedate] => 2016-04-09
        [theadults] => 3
    )

)

因此所需的输出将是这样的(也按日期排序):

So the desired output would be like this (also ordering by date):

Array
(
[0] => stdClass Object
    (
        [thedate] => 2016-02-27
        [theadults] => 1
    )

[1] => stdClass Object
    (
        [thedate] => 2016-03-05
        [theadults] => 3
    )

[2] => stdClass Object
    (
        [thedate] => 2016-04-09
        [theadults] => 24
    )

)

有人可以告诉我最有效的方法吗?在此先感谢您所提供的任何帮助.

Could anyone tell me the most efficient way to accomplish this? Thanks in advance for any help gratefully received.

推荐答案

最简单的方法似乎是将计数聚合到以日期为键的数组中.然后,您可以对键进行排序,并根据需要输出数据.

Looks like the simplest way would to be to aggregate the counts into an array with the date as the key. You could then sort on the key and output the data however you desired.

考虑一下:

$totalsByDate = [];
foreach ($array as $element) if (($date = strtotime($element->thedate)) and is_numeric($element->theadults)) {
    $totalsByDate[$date] += $element->theadults;
}
ksort($totalsByDate);
foreach ($totalsByDate as $date => $total) {
    echo "On " . date("Y-m-d", $date) . " there were " . $total " adults.\n";
}

如果您希望日期以降序排列,也可以用 krsort()替换 ksort().

You could also replace the ksort() with krsort() if you wanted the dates sorted in descending order.

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

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