当单元格达到特定限制时动态创建表格行

时间:2017-07-20 16:21:44

标签: php arrays loops html-table

我想用PHP创建一个表,但我发现很难动态添加新的TABLE ROW 循环CELL已经是4。

示例:下面的代码会给我这个:

<table>
<td>CELL1</td><td>CELL2</td><td>CELL3</td><td>CELL4 </td><td>CELL5</td><td>CELL6</td><td>CELL7</td><td>CELL8</td>
</table>

但我希望一旦单元格为4,它将为其他项目创建一个新行

<table>
<tr>
<td>CELL1</td><td>CELL2</td><td>CELL3</td><td>CELL4 </td>
</tr>
<tr>
<td>CELL5</td><td>CELL6</td><td>CELL7</td><td>CELL8</td>
</tr>
</table>

我的示例代码

<?php
$string = 'wifi,pool,cafe,lunch, item1,item2,item3,item4,item5';
$tdlimit = 4;
$converArry = explode(',', $string);
$AddTable = '<table>';
foreach($converArry as $tds){
    //if(count_of_cell_is_4_create_tr){$AddTable .= '<tr>';}
    $AddTable .= '<td>'.$tds.'</td>';
    //if(count_of_cell_is_4_create_tr){$AddTable .= '</tr>';}
}
$AddTable .= '</table>';
?>

2 个答案:

答案 0 :(得分:0)

尝试下面的内容,我还没有尝试过。

$string = 'wifi,pool,cafe,lunch, item1,item2,item3,item4,item5';
$tdlimit = 0;
$converArry = explode(',', $string);
$AddTable = '<table>';
$AddTable = '<tr>';
foreach($converArry as $tds){
    if($tdlimit%4 == 0){
        $AddTable .='</tr>';
        $AddTable .='<tr>';
    }
    $AddTable .= '<td>'.$tds.'</td>';
    $tdlimit++;
}

$AddTable .='</tr>'
$AddTable .= '<table>';

答案 1 :(得分:0)

要创建这样的行,您不需要检查它是否已经是四行。您需要检查它是否可以整除四。如果你不这样做,那么你将在第一行获得四个项目,然而在第二行中有许多项目,即使这个项目超过四个。因此,您需要一些逻辑来确定何时开始新行。

您可以通过访问数组的索引并检查在将其除以4时是否有任何余数来执行此操作。

<?php
$string = 'wifi,pool,cafe,lunch, item1,item2,item3,item4,item5';
$tdlimit = 4;
$converArry = explode(',', $string);

// open a row at the beginning
$AddTable = '<table><tr>';
foreach ($converArry as $i => $tds) {  // add the array index to your loop definition

    // if the index is a multiple of four, close the current row and open a new one
    if ($i && ($i % 4 == 0)) $AddTable .= '</tr><tr>';
    $AddTable .= '<td>'.$tds.'</td>';
}

// in case the total count of items is a multiple of four, close the last row
if (($i + 1) % 4 == 0) $AddTable .= '</tr>';

$AddTable .= '</table>';