2016-08-07 62 views
3

我有兩個表一個項目表,客戶表: enter image description here動態行跨度PHP while循環

在表

你可以看到第二項項目編號1002有兩個entries.and我想合併單元格添加到第1列和第3項

enter image description here

<table> 
    <tr> 
    <th>Item ID</th> 
    <th>Item Color</th> 
    <th>Customer</th> 
    </tr> 
<?php 
$sql = mysqi_query($con,"select * from item_table"); 
while($row = mysqli_fetch_array($sql)){ 
    ?> 

<tr> 
    <td><?=$row['item_id'];?></td> 
    <td><?=$row['item_color'];?></td> 
    <td> 
     <select> 
     <?php 
     $sql_cust = mysqli_query($con,"select * from customer_tbl"); 
     while($row_cust = mysqli_fetch_array()){ 
     if($row['customer_id'] == $row_cust['customer_id']){ 
      echo "<option selected='selected' >".$row['customer_name']."</option>"; 
     }else{ 
      echo "<option>".$row['customer_name']."</option>"; 
     } 

     <?php 
     } 
     ?> 
     </select> 
    </td> 
    </tr> 


<?php 
} 
?> 
</table> 

但它在打印正常的方式,我不知道如何在loop..please添加行跨度提出了一些邏輯來解決它的讚賞。

enter image description here

回答

2

你可以試試這樣說:

首先,添加一個計數器,以您的查詢,將顯示多少個條目有一個給定的項目。

$sql_cust = mysqli_query($con, 
"SELECT *, (SELECT COUNT(*) FROM item_table as it 
WHERE it.item_id = item_table.item_id) as c 
FROM item_table"); 

然後,當在項目中循環時,您會將rowspan設置爲項目所具有的條目數。以下是整個代碼調整。

<?php 
$sql = mysqi_query($con, 
    "SELECT *, (SELECT COUNT(*) FROM item_table as it 
    WHERE it.item_id = item_table.item_id) as entry_count 
    FROM item_table"); 
$buffer = []; 
while($row = mysqli_fetch_array($sql)){ 
    if(!isset($buffer[$row[$item_id]])) { 
     $buffer[$row[$item_id]] = 1; 
    } 
?> 
<tr> 
    <?php if(!isset($buffer[$row[$item_id]])) {?> 
    <td rowspan="<?=$row['entry_count']?>"><?=$row['item_id'];?></td> 
    <?php }?> 
    <td><?=$row['item_color'];?></td> 
    <?php if(!isset($buffer[$row[$item_id]])) {?> 
    <td rowspan="<?=$row['entry_count']?>"> 
     <select> 
     <?php 
     $sql_cust = mysqli_query($con,"select * from customer_tbl"); 
     while($row_cust = mysqli_fetch_array()){ 
     if($row['customer_id'] == $row_cust['customer_id']){ 
      echo "<option selected='selected' >".$row['customer_name']."</option>"; 
     }else{ 
      echo "<option>".$row['customer_name']."</option>"; 
     } 

     <?php 
     } 
     ?> 
     </select> 
    </td> 
    <?php }?> 
    </tr> 


<?php 
} 
?> 

注意,我添加了一個緩衝,我設置哪些項目已經顯示。這個數組被使用,所以你只需要用想要的rowspan打開一個td,而不是在每次迭代時都這樣做。

0

我有一個簡單的想法

給予TD像

<td id="dynamically-Generate"> (you need to verify that TD id need to be equal in .rowSpan ="here" inside script ) 

,並設置該TD如果動態生成一個ID大於1,則不會顯示

,並再次,如果動態-Generate大於1然後用這個腳本

<script> 
document.getElementById("dynamically-Generate").rowSpan = "dynamically-Generate"; 
</script> 

使用腳本insi de循環和動態生成 - 每個循環內需要生成相同的內容並在每個循環後更改