0

我一直在尝试将数据库中的输出分组为时间段。

例如

2013 年 5 月

一些数据

更多数据

2013 年 6 月

一些数据

一些数据

下面的代码在一定程度上有效,但每个月只会放置一行数据,即使应该有更多。即每个月有不止一行数据

谁能解释为什么?

  function show_records($mysql_link)
  {
   date_default_timezone_set('Europe/London');
   $today=date('Y/m/d');
   $future=date('Y-m-d', strtotime("+10 months", strtotime($today)));


   $q="SELECT number,startdate,traction,tourname,start,fares,tourcompany
   FROM specials
   WHERE startdate>='$today' AND startdate<='$future' AND steam='y'
   ORDER BY startdate";


   $r=mysqli_query($mysql_link,$q);
   $lastmonth="";
   if ($r)
   {


    echo "<Table id='customers'>
    <tr>
    <th>Date</th>
    <th>Locomotive</th>
    <th>Organiser</th>
    <th>Name</th>
    <th>Pick Up Points</th>
    <th>Destination</th>
    <th>Fares</th>
    </tr>";


    while ($row=mysqli_fetch_array($r,MYSQLI_ASSOC))
    {
     $parts=explode('-',$row['startdate']);
     $timestamp=strtotime($row['startdate']);
     $parts2=date('YM',$timestamp);

 if (empty($lastmonth)|| $lastmonth!=$parts2) 
     {

     if (!empty($lastmonth))
     {
      echo '</table>';
 }
  echo "<h1>$parts2</h1>";
  echo "<table id='customers'>";
  $lastmonth=$parts2;               


      echo "<tr>";
      echo "<td>".$parts2."</td>";
      echo "<td>".$row['traction']."</td>";
      echo "<td>".$row['tourcompany']."</td>";
      echo "<td>".$row['tourname']."</td>";
      echo "<td>".$row['start']."</td>";
      echo "<td>".$row['end']."</td>";
      echo "<td>".$row['fares']."</td>";
      echo "</tr>";

      }
     echo "</Table>";
     }

    }
   else {echo '<p>'.mysqli_error($mysql_link).'</p>' ;}
   }
   show_records($mysql_link);

   mysqli_close($mysql_link);

   ?>
4

2 回答 2

1

只有在$lastmonth != $parts2. 请改用以下代码:

if (empty($lastmonth) || $lastmonth != $parts2) {
    if (!empty($lastmonth)) {
        echo '</table>';
    }
    echo "<h1>$parts2</h1>";
    echo "<table>";
    $lastmonth = $parts2;
}
echo "<tr>";
echo "<td>".... // and so on
于 2013-11-02T15:16:46.573 回答
0

在您的循环中, $lastmonth 变量仅在第一次更新。然后你只是在寻找它是“空的”,它在第一次更新后永远不会。解决这个问题,我敢打赌它会很好用!

于 2013-11-02T15:17:23.597 回答