从数据库获取每日销售 - 没有销售的天数应显示0 - 过去30天的销售额

时间:2017-03-01 10:07:20

标签: php mysql datetime

我需要创建过去30天内销售统计信息的图表。有些日子没有销售,所以我必须在这些日子里显示0。

的MySQL

SELECT COUNT(*) as total, DAY(FROM_UNIXTIME(tmstmp)) AS soldDay
FROM tl_voucher_create
WHERE sold = 1 
GROUP BY soldDay
ORDER BY tmstmp DESC 0,30

结果的PHP数组

Array
(
    [0] => Array
        (
            [total] => 1
            [soldDay] => 24
        )

    [1] => Array
        (
            [total] => 1
            [soldDay] => 13
        )

    [2] => Array
        (
            [total] => 4
            [soldDay] => 3
        )

    [3] => Array
        (
            [total] => 2
            [soldDay] => 23
        )

使用循环,我将值放入一个新数组:

for ($x = $day; $x < 31; $x++) {
    if (isset($this->_["soldDaily"][$x]["soldDay"])) {
        $total[$x] = $this->_["soldDaily"][$x]["total"];
    } else {
        $total[$x] = 0;
    }
}

如何以正确的顺序使用过去30天的值制作正确的输出?

提前致谢

1 个答案:

答案 0 :(得分:1)

将查询基于实际日期:

SELECT COUNT(*) AS total, DATE(FROM_UNIXTIME(tmstmp)) AS sold_date
FROM tl_voucher_create
WHERE sold = 1
  AND sold_date BETWEEN DATE(NOW() - INTERVAL 30 DAY) AND CURDATE()
GROUP BY sold_date
ORDER BY sold_date DESC

假设查询结果如下:

$data = [
    [
        'total' => 7,
        'sold_date' => '2017-02-28'
    ],
    [
        'total' => 19,
        'sold_date' => '2017-02-27'
    ],
    [
        'total' => 8,
        'sold_date' => '2017-02-24'
    ],
    [
        'total' => 5,
        'sold_date' => '2017-02-22'
    ],
    [
        'total' => 12,
        'sold_date' => '2017-02-21'
    ]
];

您现在需要将PHP基于实际日期对象而不仅仅是数字30迭代循环,否则您将在报告中遇到各种问题和不准确之处,因为日期并不像从1到30循环那么简单(月份有不同的天数,你不能轻易地回到上个月,夏令时问题,时区的日期不同等。)

// Organise the array by date
$dates = [];
foreach ($data as $day) {
    $dates[$day['sold_date']] = $day['total'];
}

// Loop through the last 30 days and match each iteration with the data
$d = new DateTime();
for ($i = 0; $i < 30; $i++) {

    $date = $d->format('Y-m-d');

    // If there's no data for the specified date, use zero
    $total = isset($dates[$date]) ? $dates[$date] : 0;

    echo '<p>' . $total . ' sold on ' . $date . '</p>';

    $d->modify('-1 day');
}