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 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?
  • ¥100 求三轴之间相互配合画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了