以24小时为间隔显示总和

时间:2019-06-13 09:08:28

标签: php symfony datetime doctrine-orm symfony-3.4

我编写了一个函数,该函数需要返回最近24小时内的交易总数。 我当前的代码会在一小时内返回所有交易,例如:

        {
            "Total": "22"
        },
        {
            "Total": "31"
        },
        ...

我需要24小时内完成的所有交易的总金额。我认为这是DateTimeInterval或类似问题。我检查了文档,但找不到解决方案。

我的代码:

$resultDay = $this->getMyRepository()
        ->createQueryBuilder('p')
        ->select('DATE_FORMAT(p.transactionDate, \'%H\') as Time, sum(p.amount) Total')
        ->where('p.transactionDate >= :end')
        ->andWhere('p.user = :user')
        ->setParameter('end', new \DateTime('-24 hours'))
        ->setParameter('user', $user)
        ->groupBy('p.transactionDate')
        ->getQuery()
        ->getArrayResult();

    $result = array(
        "labels" => array(),
        "data"   => array(),
    );

    $days = [];
    $start    = (new \DateTime('-24 hours'));
    $end      = (new \DateTime());
    $interval = \DateInterval::createFromDateString('1 hour');
    $period   = new \DatePeriod($start, $interval, $end);

    foreach ($period as $dt) {
        $days[] = $dt->format("H");
    }


    $result['labels'] = $hours;
    $result['data'] = array_fill(0, count($hours), 0);


    foreach($resultDay as $hourSpending){
        foreach($result['labels'] as $index => $label) {
                $result['data'][$index] =  $hourSpending["Total"];
        }
    }

    return $resultDay;

我该如何解决?我希望它是24小时的总和,例如:

        {
            "Total for 24h": "53"
        },

0 个答案:

没有答案