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条)

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改