PHP将数据映射到HTML表,同时跳过一些html表列

时间:2017-03-29 14:38:36

标签: php html

ALO,

我在php中有这个数组:

$data=array(1,2,3,4,5,6,7,8);

我想将它放在具有以下结构(图像)的html表中

Mike Wasson's blog

要完全跳过彩色列。我没有这样做,但无论如何这是我的尝试:

$totalColumnsPerRow=8;
$skippableColumns=array(3,6,7,8);
$counter=1;
//loop the array now
$row="<tr>";
foreach($data as $val){
//do we need to start a new row or not?
 if ($counter==$totalColumnsPerRow){
 //close open row and create a new one.
 $counter=1;
 $row.="</tr><tr>":
  }

 //show I skip the current column or not?
 if(in_array($counter,$skippableColumns)){
 //skip column then add current value
 $row.="<td></td>";
 $row.="<td>$val</td>";
 }
 else{
 $row.="<td>$val</td>";
  }
 $counter++;
}

这给了我下面的表格结构。如果它已成功跳过行,则新行将以值5开始。

enter image description here

这是enter image description here

关于如何暂停循环并在可用列中使用它的任何想法?我的方法是否实用?

2 个答案:

答案 0 :(得分:1)

我修改了你的代码。请尝试以下方法。添加了评论以便更好地理解。

<table border="1" width="600px">
<tr>
<td>A</td><td>B</td><td>ABT</td><td>C</td><td>D</td><td>CDT</td><td>ACT</td><td>TTT</td>
</tr>

<?php

$data = array(1,2,3,4,5,6,7,8);
$totalColumnsPerRow = 8;
$skippableColumns = array(3,6,7,8);

$table = '<tr>';
$lastIndex = 0;

for($i = 1; $i <= $totalColumnsPerRow; $i++) { // Per column

    if(in_array($i, $skippableColumns)) { // Skipping coulmn value
        $table .= '<td></td>';
    } else { // Adding coulmn value
        $table .= '<td>'.$data[$lastIndex].'</td>';
        $lastIndex++; // Incrementing data index
    }

    if($i == $totalColumnsPerRow) { // Last column
        $table .= '</tr>'; // Ending row

        if($lastIndex <= count($data) -1) { // Data left
            $table .= '<tr>'; // Starting new row

            $i = 0; // Resetting so in the next increment it will become 1
        }
    }
}

echo $table;
?>

输出是 enter image description here

答案 1 :(得分:0)

我修改了你的代码,在同一个循环中(使用相同的$ val数据)重新检查,很少使用,备受mal goto控制。对现有代码的最小更改。

foreach($data as $val){
    //we'll come back here to decide on skip or write of next row when a skippable is encountered
    //this keeps us locked onto the same $val until it is written out
    recheck: 
    //do we need to start a new row or not?
    if ($counter==$totalColumnsPerRow){
    //close open row and create a new one.
        $counter=1;
        $row.="</tr><tr>";
    }

    //show I skip the current column or not?
    if(in_array($counter,$skippableColumns)){
    //skip column then add current value
        $row.="<td></td>";
        $counter++;
        goto recheck;
    //   $row.="<td>$val</td>";
    }
    else{
        $row.="<td>$val</td>";
    }
    $counter++;
}