例如,我有一个包含8个数据的数组。我想以这种格式显示
$a = array(1,2,3,4,5,6,7,8);
======
1 2
3 4
5 6
7 8
=====
包含11个数据的OR数组
$a = array(1,2,3,4,5,6,7,8,9,10,11);
=========
1 2 3
4 5 6
7 8 9
10 11
=========
不知道我哪部分写错了。这是我的代码
$a = array(1,2,3,4,5,6,7,8);
$c = ceil(count($a)/2);
echo "<table>";
for($i=0; $i<$c;$i++){
echo "<tr>";
echo '<td>'.$a[$i].'</td>';
echo '<td>'.$a[$i+1].'</td>';
}
echo "</table>";
然而,我的数据却以这种方式显示
======
1 2
2 3
3 4
4 5
=====
基本上,我想以这种格式显示我的mysql数据。但在此之前,我需要测试一下ceil函数,看看它是否有效。有人知道我的编码有什么问题吗?
由于每行有2个单元格,因此需要计算实际索引。另外,不要忘记关闭<tr>
for($i=0; $i<$c;$i++){
echo "<tr>";
echo '<td>'.$a[$i * 2].'</td>';
echo '<td>'.$a[$i * 2 + 1].'</td>';
echo '</tr>';
}
下面是一个完整的清洁解决方案示例:
<?php
$a = array(1,2,3,4,5,6,7,8);
$cols = 2;
$c = ceil(count($a) / $cols);
echo "<table>";
for($i = 0; $i < $c; $i++){
echo "<tr>";
for ($col = 0; $col < $cols; $col++) {
$value = isset($a[$i * $cols + $col]) ? $a[$i * $cols + $col] : '';
echo '<td>'. $value .'</td>';
}
echo "</tr>";
}
echo "</table>";
如果你手动增加它,你必须每次跳过一个循环。
$a = array(1,2,3,4,5,6,7,8,9,10,11);
$size = sizeof($a);
/* Your magic method to determine the total table cols.
*/
$cols = 3;
#$cols = 2;
echo "<table>";
for($i = 0; $i < $size; $i+=$cols){
echo "<tr>";
for($c = 0; $c < $cols; $c++){
if($i+$c >= $size){
break;
}
echo '<td>'.$a[$i+$c].'</td>';
}
echo "</tr>";
}
echo "</table>";
我已经使用数学方法来确定是否应该打印,因为它更快。但是,如果数组中的索引为空,则可能需要使用isset()
方法作为内部for循环中的整个代码。
if(isset($a[$i+$c])){
echo '<td>'.$a[$i+$c].'</td>';
}