Php输出foreach到表中,指定列号


Php output foreach into table, specify column number

我想输出一个包含数千项的列表到一个5列的表中。除了如何在最后的</tr>echo之外,一切都正常。我尝试了以下代码的几种变体,但要么以一列结束,要么以无限列结束。如果它只有两列,我可以用另一种方法来做。但我需要5来优化空间。问题是,如何使用php

将文件名列表输出到5列
    <?php
$i=0;
foreach ($files as $file) {
if ($i==4) { echo '</tr>'; 
    $i=0;
}
elseif ($i=0) { echo '<tr>'; 
}
echo '<td>
        <div>'.$file.'</div>
    </td>';
$i++; 
}
?>

请协助

请尝试使用此代码:

echo '<table><tr>'; 
for($i=0; $i<count($files); $i++) { 
    if ($i%5 == 0) { 
        echo '</tr>';
        echo '<tr>'; 
    }       
    echo '<td>
            <div class="select-all-col"><input name="select[]" type="checkbox" class="select" value="'.$files[$i].'"/>
            <a href="download-ui.php?name='.$foldername."/".$files[$i].'" style="cursor: pointer;">'.$files[$i].'</a></div>
            <br />
        </td>';
}
echo '</table>';

正如我所评论并引用的一个类似的线程一样,这里您有一个示例来获得您想要的内容。这将创建一个具有正确的colcount和行数的表。

$td = array();
$cols = 5;
foreach( $files as $i => $file ) {
    if ( $i != 0 && $i%$cols == 0 ) {
      $td[] = '<td> ' . implode( '</td><td>', $tdata ) . '</td>';
      $tdata = array();
    }
    $tdata[] = '<div class="select-all-col">
                  <input name="select[]" type="checkbox" class="select" value="' . $file . '"/>
                  <a href="download-ui.php?name=' . $folderName . '/' . $file . '" style="cursor: pointer;">' . $file . '</a>
                </div>
                <br />';
}
// fill up empty cols at the end IF cols vs data dont add up
if ( !empty( $tdata ) ) {
    $create = $cols - count( $tdata );
    for ( $i = 1; $i <= $create; $i++ ) {
        $tdata[] = ' - ';
    }
    $td[] = '<td> ' . implode( '</td><td>', $tdata ) . '</td>';
}
echo '<table><tr>' . implode( '</tr><tr>', $td ) . '</tr></table>';

或者以你的方式,这也可以工作,但在最后留下不正确的列数,如果数据列表不匹配填充5列

$i = 0;
$tdata = false;
foreach ( $files as $file ) {
  if ( $i != 0 && $i%5 == 0 ) { 
    $tdata .= '</tr><tr>';
  }
  $tdata .= '<td>
               <div class="select-all-col"><input name="select[]" type="checkbox" class="select" value="'.$file.'"/>
                 <a href="download-ui.php?name='.$folderName."/".$file.'" style="cursor: pointer;">'.$file.'</a>
               </div>
               <br />
             </td>';
  $i++; 
}
echo '<table><tr>' . $tdata . '</tr></table>';