如何使用php和mysql在每天的每次更改中循环显示结果并显示一周中的某一天?

如何使用php和mysql在每天的每次更改中循环显示结果并显示一周中的某一天?

问题描述:

with my current query and loop:

$sched = mysql_query("SELECT * 
FROM  `shows` 
ORDER BY  `shows`.`show_time` ASC")
or die(mysql_error());  


echo "<ul>";

while($row = mysql_fetch_array($sched)){
echo "<li><a href=\"#$row[id]\">";
echo $row['title'];
echo "</li>";
}
echo "</ul>";

This works great for displaying my results like this:

  • Name of show 1
  • Name of show 2
  • Name of show 3

However, I want to add an item to the list at the beginning of every change in day so it would display as follows:

  • Monday
  • Name of show 1
  • Name of show 2
  • Tuesday
  • Name of show 3
  • Wednesday
  • Name of show 4

I can't quite wrap my brain around the loop needed to do this. It might be helpful to know that the field 'show_time' is a datetime type, so it has the information for both time and day of week.

Thanks.

使用我当前的查询和循环: p>

  $ sched =  mysql_query(“SELECT * 
FROM`show` 
ORDER BY`show``show_time`ASC”)
ot die(mysql_error());  
 
 
echo“&lt; ul&gt;”; 
 
而($ row = mysql_fetch_array($ sched)){
echo“&lt; li&gt;&lt; a href = \”#$ row [id] \“  &gt;“; 
echo $ row ['title']; 
echo”&lt; / li&gt;“; 
} 
echo”&lt; / ul&gt;“; 
  code>  pre> 
 \  n 

这非常适合显示我的结果: p>

  • 节目名称1 li>
  • 节目名称2 li> \ n
  • 节目3的名称 li> ul>

    但是,我希望在每天的每次更改开始时将一个项目添加到列表中,以便显示如下 : p>

    • 星期一 li>
    • 节目名称1 li>
    • 节目名称2 li>
    • 星期二 li>
    • 节目名称3 li>
    • 星期三 li>
    • 节目名称4 li> ul>

      我不能完全围绕完成此操作所需的循环。 知道字段'show_time'是日期时间类型可能会有所帮助,因此它包含时间和星期几的信息。 p>

      谢谢。 p>

Simple tweak:

echo "<ul>";
$curDay='';
while($row = mysql_fetch_array($sched)){
   $d=date('l',strtotime($row['show_time']));
   if($d!=$curDay){
     echo '<li>'.$d.'</li>';
   }
   $curDay=$d;
   echo '<li><a href="#',$row['id'],'">',$row['title'],"</li>";
}
echo "</ul>";

Initialize $curDay, and then each time through the loop, check to see if the particular day is different than the last time through the loop (or different from the initial value)

Adjust your query to sort by show_time first.

"SELECT * FROM  `shows` ORDER BY `show_time`, `shows` ASC"

Then keep track of the current day as Shad suggests, parsing show_time to determine the day.

The best way to do this is to keep a flag in your loop, and compare to the previous value.

Eg.

$previousDay = '';
while($row = mysql_fetch_assoc()) {
  if ($previousDay != date('l', $row['show_time'])) {
     echo '<h2>' . $date('l', $row['show_time']) . '</h2>';
  }
  ...
  $previousDay = date('l', $row['show_time']);
}