dongxin2734 2018-10-30 16:43
浏览 19
已采纳

仅使用值数组中的PHP创建表

I've to print a table using TCPDF for creating a PDF using PHP from an array of contents.

In my example I'll use 7 entries, but can be more or less.

$array = array(
 0 => "[ ] Option 1",
 1 => "[x] Option 2",
 2 => "[ ] Option 3",
 3 => "[ ] Option 4",
 4 => "[x] Option 5",
 5 => "[ ] Option 6",
 6 => "[ ] Option 7",
 ...
);

My table layout is dynamic: I can set numbers of columns for display purpose ( $num_cols can be 1, 2, 3 or 4 columns)

Based on my $num_cols, I've to split my content of the array in each TD cell.

So, if I set $num_cols = 4, i need to show something like that:

<table>
  <tr>
    <td>[ ] Option 1</td>
    <td>[x] Option 2</td>
    <td>[ ] Option 3</td>
    <td>[ ] Option 4</td>
  </tr>
  <tr>
    <td>[x] Option 5</td>
    <td>[ ] Option 6</td>
    <td>[ ] Option 7</td>
    <td></td>
  </tr>
</table>

I tried to start some ideas but in this example I can get only a row. I don't know how to create the external loop:

echo "<table>";
echo "<tr>";

for ( $i = 0; $i < $num_cols; $i++ ) {

 echo "<td>";
 if ( isset($array[$i]) {echo $array[$i];} else {}
 echo "</td>";

}
echo "</tr>";
echo "</table>";
  • 写回答

2条回答 默认 最新

  • doudou890510 2018-10-30 16:53
    关注

    array-chunk will help you:

    <?php
    $num_cols = 4;
    $array = [1,2,3,4,5,6,7,8];
    
    echo "<table>";
    foreach (array_chunk($array, $num_cols) as $chunk) {
        echo "<tr>";
        foreach ($chunk as $item) {
            echo "<td>";
            echo $item;
            echo "</td>";
        }
        echo "</tr>";
    }
    echo "</table>";
    

    and you can use some other cool-stuff from php :)

    <?php
    $num_cols = 4;
    $array = [1,2,3,4,5,6,7,8];
    
    echo "<table><tr><td>" .
        implode("</td></tr><tr><td>",
            array_map(function(array $part) {
                return implode('</td><td>', $part);
            }, array_chunk($array, $num_cols))
        )
    . "</td></tr></table>";
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥30 python代码,帮调试,帮帮忙吧