如何使列具有相同的值名称时如何自动rowpan表

时间:2016-08-26 07:16:19

标签: php

我有一个列表产品

Invoice No. | Product Name | Quantity
INV001      |    iPhone    |    1 
INV001      |    iPad      |    2
INV001      |    iPod      |    1 
INV002      |    iMac      |    2
INV002      |    iPhone    |    1 

将所有数据提取到数组后,当Invoice No.相同值时,如何创建表自动rowpan。

Invoice No. | Product Name | Quantity
    INV001  |    iPhone    |    1 
            |    iPad      |    2
            |    iPod      |    1 
    INV002  |    iMac      |    2
            |    iPhone    |    1 

<table>
   <tr>
      <th>Invoice No.</th>
      <th>Product Name</th>
      <th>Quantity</th>
   </tr>
   <tr>
      <td rowspan="3">INV001</td>
      <td>iPhone</td>
      <td>1</td>
   </tr>
   <tr>
      <td>iPad</td>
      <td>2</td>
   </tr>
   <tr>
      <td>iPod</td>
      <td>1</td>
   </tr>
   <tr>
      <td rowspan="2">INV001</td>
      <td>iMac</td>
      <td>2</td>
   </tr>
   <tr>
      <td>iPhone</td>
      <td>1</td>
   </tr>
</table>

2 个答案:

答案 0 :(得分:1)

您需要确保您的行按发票编号排序,然后您需要计算每个发票编号的出现次数,该值将是您的行数。

以下是一个例子:

$invoiceNbOccurences = array();
foreach($rows as $row){
  $invoiceNb = $row['invoice_nb'];

  if(!isset($invoiceNbOccurences[$invoiceNb])){
    $invoiceNbOccurences[$invoiceNb] = 0;
  }

  $invoiceNbOccurences[$invoiceNb]++;
}

以及如何使用它:

<td rowspan="<?php echo $invoiceNbOccurences['INV001'];?>"></td>
<td rowspan="<?php echo $invoiceNbOccurences['INV002'];?>"></td>

答案 1 :(得分:1)

$data = // query result
$last_key = null;
$dum_arr = array();
foreach ($data as $key => $row) {
   if($row->name == $last_key) {
      $dum_arr[] = $key;
   }

   if(!in_array($key, $dum_arr)) {
       // echo rowspan here...
   }

   $last_key = $row->name;
}