将forep输出到表中,指定列号

时间:2015-09-27 11:43:14

标签: php multiple-columns

我想将包含数千个项目的列表输出到包含5列的表中。除了前一个echo中的</tr>之外,一切都有效。我在下面的代码中尝试了几种变体,但要么以一列结束,要么以无限列结束。如果它只有两列,我可以用另一种方式。但我需要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++; 
}
?>

请协助

2 个答案:

答案 0 :(得分:1)

请尝试使用此代码:

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>';

此外,通过使用for而不是foreach,您可以确保不会因空数组而出现任何错误。

答案 1 :(得分:1)

正如我评论并提到了一个类似的主题,这里有一个例子来得到你想要的东西。这将创建一个具有正确col col和行的表。

$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>';