基于 php 数组动态创建 HTML 表行


Dynamically create HTML table rows based on php array

我正在努力抓住以下内容。我想基于 PHP 数组构建一个每行 3 个数据单元格的表。换句话说,如果数组中有 3 个值,则应该有一个这样的结构:

<?php
$arr = array("value1","value2","value3");
?>
// Expected outcome:
<table>
      <tr>
           <td>value1</td>
           <td>value2</td>
           <td>value3</td>               
      </tr>
</table>

但是如果将第 4 个值添加到数组中,它必须动态创建另一行,换句话说:

<?php
$arr = array("value1","value2","value3","value4");
?>
// Expected outcome:
<table>
      <tr>
           <td>value1</td>
           <td>value2</td>
           <td>value3</td>               
      </tr>
      <tr>
           <td>value4</td>
           <td></td>
           <td></td>               
      </tr>
</table>

我真的不介意哪种解决方案,甚至是php和jQuery之间的混合,但只是我可以用来实现上述目标的东西。

使用模数。这样:

<table>
<tr>
<?php
    $i = 1;
    foreach ($arr as $val){
        $i++;
        print '<td>'.$i.'</td>';
        if ($i % 3 == 0){
            print '</tr><tr>'^;
        }
    }
?>
</tr>
</table>

您将需要添加更多内容才能正确输出 html,但"困难"部分已经完成。

不要只是复制和粘贴,我没有测试代码,这很丑陋。

使用array_chunk函数将数组分成几组,然后只做几个循环,例如

<?php
$arr = array("value1","value2","value3","value4");
echo "<table>";
$rows = array_chunk($arr,3);
foreach($rows as $row) {
  echo "<tr>";
  foreach($row as $cell) {
    echo "<td>".$cell."</td>";
  }
  echo "</tr>";
}
echo "</table>";
?>

这是一个逻辑实现:

<?php
$input_array = array('a', 'b', 'c', 'd', 'e','f','g');
$new_array = array_chunk($input_array, 3);
$table = '<table border="1">';
foreach($new_array as $value){
$table .= '<tr><td>'.$value[0].'</td><td>'.$value[1].'</td><td>'.$value[2].'</td>    </tr>';
}
$table.='</table>';
echo $table;
?>
<table><tr>
<?php
$arr = array("value1","value2","value3","value4","value5","value6","value7");
for($i=0;$i<count($arr)%3;$i++)
  $arr[] = null;
foreach($arr as $key => $val){
  if(($key)%3==0)
    echo '</tr><tr>';
  echo '<td>'.$val.'</td>';
}
?>
</tr></table>
<table>
    <tr>
        <?php
        $x = 0;
        foreach($arr as $v){
            if ($x % 3 == 0 && $x != 0){
                echo '</tr><tr>';
            }
            echo '<td>'.$v.'</td>';
            $x++;
        }
        ?>
    </tr>
</table>
这是我

的建议,它将产生将格式化的html

<table>
    <tr>    
    <?php
    $i = 0;
    $items_per_row = 3;
    foreach ($arr as $elm) {
        echo '<td>'.$elm.'</td>';
        if (++$i % $items_per_row == 0 && $i < count($arr) - 1)
            echo '</tr><tr>';
    }
    ?>
    </tr>
</table>