简体   繁体   English

每月创建表格

[英]Create table per month

Assuming I have the following MySQL table; 假设我有以下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

I want to fetch all these results, and per month-year I want to create a HTML table: 我想获取所有这些结果,并且每个月要创建一个HTML表:

January, 2013
[*] Jane

February, 2013
[*] John doe

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

As you can see, March does not exist. 如您所见,三月不存在。 How can I produce something like this with PHP? 如何用PHP生成类似的东西?

Just order by month (and maybe title) using SQL. 只需使用SQL按月订购(可能还有标题)即可。 Then do something like this: 然后执行以下操作:

$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>';

This starts a new table every time the month changes from one record to the next. 每个月从一个记录更改为下一个记录时,都会启动一个新表。

This, of course, doesn't display empty months because they are not present in the dataset. 当然,这不会显示空月份,因为它们不存在于数据集中。

Also, it kinda looks like you actually want a list here. 另外,看起来您实际上想要在这里列出。 If that is the case, just replace <table> , </table> and <tr> in that snippet with <ul> , </ul> and <li> respectively. 如果是这种情况,只需将该片段中的<table></table><tr>替换为<ul></ul><li>

Create an array with Key as month , if you find any record for that month add to the array . 创建一个键为月的数组,如果您发现该月的任何记录,请添加到该数组中。 At the end you will have array with month as key and all the names in another array 最后,您将得到一个以月为键的数组,所有名称都在另一个数组中

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM