我有一个PDO查询来选择同一日期过去五年的日记:
$sql = 'select * from diary where dtime in (?,?,?,?,?) order by dtime desc';
$result = $db->prepare($sql);
$result->execute($fiveYears); //pass in the $fiveYear array of five dates like 2014-03-01, 2013-03-01 ~ 2010-03-01
然后我使用这样的foreach循环回显结果:
foreach($result as $row){
~~echo table contents here~~
}
我想在五个表中显示内容,即使那一年没有内容,但是foreach循环只回显了包含内容的日期。因此,如果有2014-03-01和2012-03-01的内容,结果是:
但我想要它显示
你能帮助我如何实现这个目标吗? 我应该将$ fiveYear数组与结果数组合并吗?怎么样? 我应该在PHP中使用in_array吗? 或者有更好的方法吗? 谢谢!
答案 0 :(得分:2)
嗯,因为这个简单的任务需要比当地人更多的理解(甚至需要阅读问题正文!)
$date_start = '2012-03-01';
$date_end = '2012-03-31';
$range = array();
$date = $date_start;
while ($date <= $date_end)
{
$range[] = $date;
$date = date("Y-m-d", strtotime("$date + 1 day"));
}
$sql = 'select * from diary where dtime BETWEEN ? AND ? order by dtime desc';
$stm = $db->prepare($sql);
$stm->execute(array($date_start, $date_end));
$result = array();
while ($row = $stm->fetch())
{
$result[$row['dtime']] = $row;
}
?>
<?php foreach ($range as $day): ?>
<?=$day?>:
<?php if (isset($result[$day])): ?>
diary entry <?=$result[$day]['title']?>
<? else: ?>
empty
<? endif ?>
但是,如果dtime包含datetime值,顾名思义,它将不起作用。您需要在查询中选择DATE(dtime) as dtime, *