drqwbh2150 2013-02-17 18:44
浏览 22
已采纳

在PHP中填写日期对象数组中缺少的元素

I have an array of objects in php which looks like:

Array
(
    [0] => Array
      (
        [day] => 1/23/2013
        [executions] => 1
      )

    [1] => Array
      (
        [day] => 1/24/2013
        [executions] => 1
      )

    [2] => Array
      (
        [day] => 1/27/2013
        [executions] => 10
      )

    [3] => Array
      (
        [day] => 1/29/2013
        [executions] => 1
      )

    [4] => Array
      (
        [day] => 1/30/2013
        [executions] => 3
      )

    [5] => Array
      (
        [day] => 2/8/2013
        [executions] => 1
      )

   [6] => Array
      (
        [day] => 2/11/2013
        [executions] => 3
      )

)

I am building a graph of this data, and basically it represents the last 30 days. The problem is I don't get the missing days, i.e. when there was no executions from the query. I am looking to fill in these missing days with PHP, simple set the day to the correct date, and executions to 0. Thus the result array should contain 30 elements, assuming start is 1/18/2013 and end is today 2/17/2013.

Any idea of the best algorithm to accomplish this in PHP?

  • 写回答

3条回答 默认 最新

  • dq13733519262 2013-02-17 18:53
    关注

    Something like:

    $start = '1/18/2013';
    $end = '2/17/2013';
    
    $range = new DatePeriod(
      DateTime::createFromFormat('m/d/Y', $start),
      new DateInterval('P1D'),
      DateTime::createFromFormat('m/d/Y', $end));
    
    $filler = array();
    
    foreach($range as $date)
      $filler[] = array(
        'day'      => $date->format('m/d/Y'),
        'execution' => 0,
      };
    
    $array += $filler;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 安装svn网络有问题怎么办
  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献