将数组转储到表中

问题描述

| 我有一个要转储到表中的数组,但是有一个新的X列项。例如: 项目1 |项目2 |项目3 |项目4 | 项目5 |项目6 |项目7 |项目8 | 项目9 |等等... 我已经可以使用以下代码在一定数量的项目(在本例中为4)之后添加一个新列:
$input = array(\'one\',\'two\',\'three\',\'four\',\'five\',\'six\',\'seven\',\'eight\',\'nine\',\'ten\'); 

$cols = 4; 

echo \"<table border=\\\"5\\\" cellpadding=\\\"10\\\">\"; 

for ($i=0; $i < count($input); $i++) 
{ 
echo \"<tr>\"; 
    for ($c=0; $c<$cols; $c++) 
    {
    $n = $i+$c;
    echo \"<td>$input[$n]</td>\"; 
    } 
echo \"</tr>\"; 
$i += $c; 
} 

echo \"</table>\"; 
但是由于某种原因,在一列以“'四'”结束之后,下一列以“'六”开始。     

解决方法

数组函数可能非常神奇:
$input = array(\'one\',\'two\',\'three\',\'four\',\'five\',\'six\',\'seven\',\'eight\',\'nine\',\'ten\'); 
$cols = 4; 
$table = array_chunk($input,$cols);

echo \"<table border=\\\"5\\\" cellpadding=\\\"10\\\">\";

foreach($table as $row) {
    echo \"<tr>\"; 
    foreach($row as $cell) {
        echo \"<td>$cell</td>\"; 
    }
    echo \"</tr>\"; 
}
echo \"</table>\";
参考:http://php.net/manual/en/function.array-chunk.php     ,在您的第一个循环上,$ i将增加$ c(始终为3)。然后for循环会将$ i值增加一($ i ++),这将使其跳过\'five \'。 您可以控制增量,也可以让for循环为您控制增量。     ,
$input = array(\'one\',\'ten\'); 

$cols = 4; 

echo \"<table border=\\\"5\\\" cellpadding=\\\"10\\\">\"; 

for ($i=0; $i < count($input); $i++) 
{ 
echo \"<tr>\"; 
    for ($c=0; $c<$cols; $c++) 
    {
    $n = $i+$c;
    echo \"<td>$input[$n]</td>\"; 
    } 
echo \"</tr>\"; 
$i += $c - 1; 
} 

echo \"</table>\";
凯的答案是一个更好的解决方案。我所做的只是从
$i += $c
行中减去1。     ,您每5次跳过一次,因为当您检测到需要执行新行时,将使用for循环将计数器增加额外的时间。 这是另一个方案:
$ary = array(\'item1\',\'item2\',\'item3\',\'item4\',\'item5\',\'item6\',\'item7\',\'item8\');


echo \"<table><tr>\";
foreach($ary as $k => $item)
{
    if($k % 4 == 0 && $k != 0)
        echo \"</tr><tr>\";
    echo \"<td>$item</td>\";
}
echo \"</tr></table>\";
    ,如果清楚地理解了您,您想转储一个数组,该数组的数目由您指定:
for ($i=0; $i < count($input); $i++) 
{ 
echo \"<tr>\"; 
    for ($c=0; $c<$cols; $c++) 
    {
    echo \"<td>$input[$i]</td>\"; 
    } 
echo \"</tr>\"; 
} 
    ,如果您想保持原来的逻辑,请将
$i
的增量更改为
$i += (c$-1)
,因为除了列宽外,您还增加了循环中的
$i
。然后还要满足空值。这将起作用:
<?php
$input = array(\'one\',\'ten\'); 

$cols = 4; 

echo \"<table border=\\\"5\\\" cellpadding=\\\"10\\\">\" . PHP_EOL; 

for ($i=0; $i < count($input); $i++) 
{ 
echo \"<tr>\"; 
    for ($c=0; $c<$cols; $c++) 
    {
    $n = $i+$c;
    if ( $n < count($input))
        echo \"<td>$input[$n]</td>\" . PHP_EOL; 
    else
        echo \"<td></td>\" . PHP_EOL;
    } 
echo \"</tr>\"; 
$i += ($c-1); 
} 

echo \"</table>\"; 
?>
    

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...