2017-09-04 115 views
1

這是我的代碼,我使用while循環從數據庫中獲取行值。如何在php中使用while循環獲取類別值

<?php 
$query = "SELECT I.itemid AS itemid, C.catid AS catid, C.name AS cname, I.name AS iname, I.price As price FROM tbl_item I INNER JOIN tbl_menu_category C ON I.catid=C.catid;" 
$sql = mysqli_query($con, $query); 

while($row=mysqli_fetch_array($sql)) { ?> 

<ul class="menu-cat" id="menu<?php echo $row['catid'];?>"> 
<li> 
<h5><?php echo $row['cname'];?></h5> 
<span><?php echo $row['iname'];?></span> 
    <span style="float:right"><?php echo $row['iprice'];?></span> 
<span><i class="fa fa-plus-circle" aria-hidden="true"></i></span> 

</li> 
    </ul> 

    <?php } ?> 

一切工作正常,但我希望類別出現一次,因爲它顯示多次。

組別 娃娃25

組別 汽車50

產品組別 連衣裙400

產品組別 禮品100

我想說明如下

組別

娃娃25 汽車50

CATEGORY2

連衣裙400 禮品100

我怎麼就能達到同樣??

回答

1

存儲迭代的最後一個類別的名稱並將其與當前類別進行比較。如果不同,打印它,如果不是,則不要:

<?php 
$query = "SELECT I.itemid AS itemid, C.catid AS catid, C.name AS cname, I.name AS iname, I.price As price FROM tbl_item I INNER JOIN tbl_menu_category C ON I.catid=C.catid;" 
$sql = mysqli_query($con, $query); 
$lastCategory = null; 
while($row=mysqli_fetch_array($sql)) { 
    ?> 
    <ul class="menu-cat" id="menu<?php echo $row['catid'];?>"> 
     <li> 
      <?php if ($lastCategory === null || $lastCategory !== $row["cname"]):?> <h5><?php echo $row['cname'];?></h5><?php endif;?> 
      <span><?php echo $row['iname'];?></span> 
      <span style="float:right"><?php echo $row['iprice'];?></span> 
      <span><i class="fa fa-plus-circle" aria-hidden="true"></i></span> 
     </li> 
     </ul> 
    <?php 
    $lastCategory = $row["cname"]; 
} 
?>