我在array
中有一个objects
php
,如下所示:
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
设置为正确的日期,将executions
设置为0
。因此,结果数组应包含30个元素,假设start为1/18/2013
,end为today 2/17/2013
。
想知道在PHP中实现这一目标的最佳算法吗?
答案 0 :(得分: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;
答案 1 :(得分: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");
}
答案 2 :(得分: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个项目都没问题!