每月创建表

时间:2013-04-04 10:50:34

标签: php mysql

假设我有以下MySQL表格;

id      | title   | date
--------+---------+----------
0       | john doe| 2013-02-01
2       | tarzan  | 2013-04-01
9       | toy-box | 2013-04-02
11      | jane    | 2013-01-01

我想获取所有这些结果,并且每个月我想创建一个HTML表格:

January, 2013
[*] Jane

February, 2013
[*] John doe

April, 2013
[*] Tarzan
[*] toy-box

如您所见,March不存在。我怎么用PHP生成这样的东西?

2 个答案:

答案 0 :(得分:4)

使用SQL按月(也许是标题)排序。然后做这样的事情:

$lastMonthId = null;

foreach ($records as $record) {
    $date = strtotime($record['date']);

    $monthId = date('Ym', $date);
    if ($monthId !== $lastMonthId) {
        if ($lastMonthId !== null) echo '</table>';
        echo '<h1>', date('Y-m', $date), '</h1>';
        echo '<table>';

        $lastMonthId = $monthId;
    }

    // Output <tr> for this record.
}

echo '</table>';

每次月份从一个记录更改为下一个记录时,都会启动一个新表。

当然,这不显示空月,因为它们不存在于数据集中。

另外,看起来你真的想要一个列表。如果是这种情况,只需将该代码段中的<table></table><tr>分别替换为<ul></ul><li>

答案 1 :(得分:1)

如果您发现该月的任何记录添加到数组,则创建一个Key为月的数组。最后,您将拥有以月为键的数组以及另一个数组中的所有名称

         $myData = array()
         while(Looping through DB record)
        {
             extract Month part and check array_key_exists($myData , monthPart)
            if yes then $myData[$key]['Name'] = UserName
        }
相关问题