此脚本将生日作为标题和下面的客户输出。
因此输出按出生日期“分组”。
echo "<div>";
foreach(pdo_query("SELECT customer, birthday FROM table ORDER BY birthday ASC", array($empty)) as $row)
{
if(!isset($birthday) or $birthday != $row['birthday'])
{
unset($drawline);
echo "</div>";
echo "<div class=title><h1>".$row['birthday']."</h1></div><div class=customer>";
}
if(isset($drawline)){echo "<hr>";}
echo $row['customer']."<br>";
$drawline = 1;
$birthday = $row['birthday'];
}
echo "</div>";
'birthday'是数据库中的DATE字段。
在客户之间总是有一条线(小时),但不是在d.o.b的最后一个客户之后。
示例输出:
<div class=title><h1>1986-10-08</h1></div>
<div class=customer>
Don Foo<br>
<hr>
Joe Bar<br>
</div>
<div class=title><h1>1988-03-18</h1></div>
<div class=customer>
Jane Fonda<br>
<hr>
Elvis Burns<br>
</div>
是否可以删除<div>
之外的</div>
和foreach()
?
它始终为空<div></div>
。
答案 0 :(得分:2)
我已经决定程序员在看这里发生了什么事情时会有太多的麻烦,所以这里的代码版本要干净得多。
<?php
$people = pdo_query("SELECT customer, birthday FROM table ORDER BY birthday ASC", array($empty));
if (!empty($people)) {
// Find out people with the same birthday and group them.
$birthdays = [];
foreach ($people as $man) {
$birthday = $man['birthday'];
if (empty($birthdays[$birthday])) {
$birthdays[$birthday] = [];
}
$birthdays[$birthday][] = $man['customer'];
}
// Now let's output everything!
?>
<div>
<?php foreach ($birthdays as $birthday => $customers): ?>
<div class=title><h1><?= $birthday ?></h1></div>
<div class="customer">
<?= implode('<br><hr>', $customers) ?>
</div>
<?php endforeach;?>
</div>
<?php } // endif (!empty($people)) ?>
此解决方案的要点 - 非常简单易懂,使用一些模板(您可以为这个小片段创建一个),易于调试和修改。是的,它不再输出空<div></div>
了!