一旦PHP显示来自MySQL DB的重复值

时间:2015-02-06 15:13:57

标签: php mysql

我在MySQL DB中有一个表,它存储了餐厅在每个工作日和时间段提供的菜单。

表结构如下:

  i_type      i_name    i_cost   i_day   i_start     i_end
  --------------------------------------------------------
  Breakfast   Prantha   20       Sunday   07:00      11:00
  Lunch       Special   80       Sunday   11:01      15:00
  Dinner      Special   100      Sunday   15:01      21:00
  Breakfast   Prantha1  50       Monday   07:00      11:00
  Lunch       Special1  70       Monday   11:01      15:00
  Dinner      Special1  130      Monday   15:01      21:00

我想显示如下菜单:

<b>Sunday</b><br/>
    Breakfast<hr/>Prantha       20     Add<br/><br/>
    Lunch<br/><hr/>Special      80     Add<br/><br/>
    Dinner<br/><hr/>Special     100    Add<br/><hr/>
<b>Monday</b><br/>
   Breakfast<hr/>Prantha       20     Add<br/><br/>
   Lunch<br/><hr/>Special      80     Add<br/><br/>
   Dinner<br/><hr/>Special     100    Add<br/><hr/>

目前我正在处理如下:

$sql = SELECT * FROM `tabl1` WHERE 1;      
$data = DB::instance()->prepare($sql)->execute()->fetchAll();
foreach($data as $row){
       //print values
 }

but this approach print Sunday and Monday multiple times. 

3 个答案:

答案 0 :(得分:1)

当然会打印三个星期日和三个星期一。

例如,您可以先选择所有不同的日期(SELECT DISTINCT(i_day)FROM菜单),然后每天选择所有菜单(SELECT * FROM menu WHERE i_day =?)

$sql = "SELECT DISTINCT (i_day) FROM menu";      
$data = DB::instance()->prepare($sql)->execute()->fetchAll();
foreach($data as $row){
  // Add all i_day's to an associative array $i_days
}
foreach($i_days as $day) {
  $sql = "SELECT * FROM menu WHERE i_day = $day";      
  $data = DB::instance()->prepare($sql)->execute()->fetchAll();
    foreach($data as $row){
      // Print values
    }
}

答案 1 :(得分:1)

只需跟踪您输出的日期,例如使用&#34;状态机&#34;:

$previousday = null;
while($row = ... fetch from db... ) {
    if ($row['day'] != $previousday) {
       ... output day header
       $previousday = $row['day'];
    }
    ... output row data ...
}

答案 2 :(得分:-1)

试试这个:

$stat = "SELECT * from TABLE_NAME";
$conn -> query ($stat);
foreach($conn -> query($stat) as $menu) {

echo $menu["i_day"];
echo $menu["i_type"];
echo $menu["i_name"];
echo $menu["i_cost"];

}

根据您的需要格式化上述数据。我刚给你提供了基本代码。

可替换地,

$stat = "SELECT * from TABLE_NAME where i_day = 'DAY_GOES_HERE'";
$conn -> query ($stat);
foreach($conn -> query($stat) as $menu) {

echo $menu["i_type"];
echo $menu["i_name"];
echo $menu[i_cost];

}

每天重复一次。