php

时间:2016-01-06 06:29:36

标签: php

我在做一个动态表时遇到问题

我的表结构如下:

======================================================================
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;
     }

脚本有点长,所以我刚刚提供了与shelflife相关的记录。

1 个答案:

答案 0 :(得分:0)

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

$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>";

编辑:添加了表格标签