繁体   English   中英

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

[英]PHP map array data to HTML table while skipping some html table columns

阿罗

我在php中有这个数组:

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

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

在此处输入图片说明

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

$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开始。

在此处输入图片说明

这是一个PHP小提琴

关于如何喜欢暂停循环并在可用列中使用它的任何想法吗? 我的方法可行吗?

我修改了您的代码。 请尝试以下方法。 添加了注释以便更好地理解。

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

输出是 在此处输入图片说明

我修改了您的代码,以在很少使用,非常有害的goto控件的同一循环(使用相同的$ val数据)内重新检查。 对现有代码的最小更改。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM