1

我有一个array看起来像objectsphp

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
      )

)

我正在构建这些数据的图表,基本上它代表过去 30 天。问题是我没有得到丢失的日子,即当查询没有执行时。我希望用 PHP 来填补这些缺失的日子,只需将 设置day为正确的日期,然后executions0. 因此,结果数组应该包含 30 个元素,假设 start 是1/18/2013并且 end 是 today 2/17/2013

知道在 PHP 中实现这一目标的最佳算法吗?

4

3 回答 3

5

就像是:

$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;
于 2013-02-17T18:53:54.600 回答
2

使用 DateTime 循环遍历每个日期:

$start = new DateTime('2013-01-18');
$end = new DateTime('2013-02-17');
while ($start <= $end)
{
    $current_date = $start->format('m/d/Y');
    // Right here look in your array and see if that date exists
    // and do whatever you need to do if it does/does not
    $start->modify("+1 day");
}
于 2013-02-17T18:49:15.517 回答
1

你可以使用这个:

$startDate = new DateTime ( "-30 days" );
$dateItter = new DatePeriod ( 
    $startDate,
    new DateInterval ('P1D'),
    30  
);

$original = array (
    array ( 
        'days' => '02/16/2013',
        'executions' => 5
    )   
);

$result = array (); 

foreach ( $dateItter as $date )
{
    $executions = 0;

    foreach ( $original as $item ) { 
        if ( $item['days'] == $date->format ( 'm/d/Y' ) ) 
            $executions = $item['executions'];
    }   

    $result[] = array (
        "day" => $date->format ( 'm/d/Y' ),
        "executions" => $executions
    );  
}

var_dump ( $result );

数据量大时速度慢,但30个项目就可以了!

于 2013-02-17T19:20:32.180 回答