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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?