duanbushi1867 2017-03-01 12:55
浏览 80
已采纳

在php中垂直填充表格

I'd like to fill a table vertically. For example one name on one row, the age on the second row alternately, and limit the table to 4 columns:

table

Is this possible with this kind of code?

Here is my Code:

<?php
$age = array("26","16","17","19","24","30");
$name = array("adam","andrew","tim","mike","don","eddy");
echo "<table border=1>";
for($i=0;$i<count($age);$i++)
{
    if ($i > 0 && $i % 4 == 0)
    {
        echo "</tr><tr>";
    }
    echo "<td>";
    echo $name[$i];
    echo "</td>";
    echo "<td>";
    echo $age[$i];
    echo "</td>";
}
echo "</tr>";
?>
  • 写回答

2条回答 默认 最新

  • dousou2897 2017-03-01 13:35
    关注

    Please try this. It is not the most elegant way but will give you an idea and maybe improve your answer. I will suggest you maybe use multi-dimensional array to store age and name together.

    $age = array("26","16","17","19","24","30");
    $name = array("adam","andrew","tim","mike","don","eddy");
    $ageChunks  = array_chunk($age,  4); //divide age array into chunks of 4
    $nameChunks = array_chunk($name, 4); //divide name array into chunks of 4
    
    //print table data
    function printData($td)
    {
        echo "<td>&nbsp;".$td."&nbsp;<td>";
    }
    
    //print table row. Assumption here is $nameChunks and $ageChunks are same length.
    function printRow($nameChunks, $ageChunks)
    {
        foreach ($nameChunks as $key=>$val) {
            echo "<tr>";
            array_map("printData", $nameChunks[$key]);
            echo "</tr><tr>";
            array_map("printData", $ageChunks[$key]);
            echo "</tr>";
        }
    }
    
    //print table
    function printTable($nameChunks, $ageChunks)
    {
        echo "<table>";
        printRow($nameChunks, $ageChunks);
        echo "</table>";
    }
    
    printTable($nameChunks, $ageChunks);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题