2016-08-07 17 views
3

私持っている二つのテーブル1項目テーブルと顧客テーブル:テーブル内の enter image description here動的な行スパンのphp whileループ

あなたは1002年の2つ持っている2番目の項目の項目IDを参照することができentries.and私はそれにはcolspanを追加しますアイテム欄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にROWSPANを追加する方法を見当がつかないその感謝を解決するためにいくつかのロジックを示唆しています。

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 
} 
?> 

既に表示されている項目を設定するバッファを追加しました。この配列は、すべての反復ではなく、必要な行スパンで1つの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ループと両方の動的 - everyloop内で同じものを生成し、ループごとに変更する必要があります。