2016-08-07 59 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循环和动态生成 - 每个循环内需要生成相同的内容并在每个循环后更改