php中的动态标题和表格单元格


Dynamic heading and table cells in php

我在做dyanamic表时遇到问题

我的表格结构如下:

======================================================================
tender_id | coc | datasheet | datecode | shelflife | Suppliername
======================================================================
   201    |  No |   Yes      |     Yes  |     No   |  Supplier1
   201    | Yes |   No       |     Yes  |     No   |  Supplier2
   201    | No  |   No       |     No   |     No   |  Supplier3

我在PHP中的预期结果是

=============================================
 COC | Datasheet | Date Code | Supplier Name
=============================================
   -     Yes          Yes       Supplier1
  Yes    -            Yes       Supplier2

只有当值为"是"时,结果才会显示。如果所有值都为"否",则不应显示标题。例如,在上述条件中,所有供应商的保质期值均为"否"。在这种情况下,即使是标题也不应该显示。我试过一些脚本,但有一些问题。

这是我尝试过的脚本:

$sql_shelf = "SELECT tender_id, suppliername, coc, date_code, shelf_life , datasheet FROM comparitive_statement1 WHERE (coc='Yes' OR technical_compliance='Yes' OR date_code='Yes' OR shelf_life='Yes' OR datasheet='Yes') tender_id='$tender_id' group by suppliername";
    $result = mysql_query($sql_shelf) or die($sql_shelf."<br/><br/>".mysql_error());
    $i = 0;
    while ($list = mysql_fetch_array($result)) {
    if($i == 0){
    echo '<tr>';
    $sh = $list['shelf_life'];
    if ($sh=="No") {
    } else {
    echo '<td><b>Shelf Life</b></td>';
    }
      echo '</tr>';
      $i++;
      }
    echo '<tr>';
    $sl1 = $list['shelf_life'];
    if ($sl1=="No") {
    } else {
    echo "<td>{$list['shelf_life']}</td>";'
    echo "</tr>";
    }
     ++$i;
     }

剧本有点长,所以我刚刚把与保质期有关的记录放了下来。

为了确定是否应该显示整列,您需要首先遍历所有记录。我还没有调试以下内容,但希望如果它不起作用,就足以让你知道需要做什么:

$result = mysql_query($sql_shelf) or die($sql_shelf."<br/><br/>".mysql_error());
$stuff = array(); //an array for all of the rows
$columns = array(); //an array for the columns
while ($list = mysql_fetch_array($result,MYSQL_ASSOC)) {
    $stuff[] = $list; //add list to the appropriate array
    if(empty($columns)) { foreach($list as $key=>$val) { $columns[$key] = 0; } } //fill $columns with a dynamic number of 0s based on how many columns the database returns
    foreach($list as $key=>$val) { if(!is_numeric($val) && $val!= 'No') { $columns[$key] = 1; } } //sets column array value to 1 for any non-numeric/non-no answer
}
//now we actually build the table
echo "<table><thead>";
echo "<tr>";
foreach($columns as $name=>$display){
    if($display== 1) { echo "<th>".$name."</th>"; } //if we set the value earlier to 1, then we want the column to show
}
echo "</tr></thead><tbody>";
foreach($stuff as $list){
    echo "<tr>";
        foreach($list as $key=>$val){
            if($columns[$key] == 1){ echo "<td>".$val."</td>";
        }
    echo "</tr>";
}
echo "</tbody></table>";

编辑:添加了表格标签