table + foreach - 新专栏?

时间:2011-09-06 10:49:17

标签: php html foreach html-table

<?php
$values = array();
for($i=0;$i<100;$i++){
 $values[$i] = "aaa" . $i;
} ?>
<table>
<?php
foreach ($values as $i => $val) {

echo "<tr><td>" . $val . "</td> </tr>";
} ?>
</table>

这让我产生了:

aaa1
aaa2
...
aaa50
...
aaa90
...
aaa100

如何制作两列?

aaa1   aaa50
aaa2   ....
...    aaa90
aaa50  aaa100

但没有:

aaa1 aaa2
aaa3 aaa4
...  ....
aaa99 aaa100

4 个答案:

答案 0 :(得分:1)

尝试这是否适合您。无论$ values中包含的项目的格式如何,它都应该按照您想要的方式打印数组。

<?php

$size = count($values);
$halfSize = intval(ceil($size / 2));

for ($i = 0; $i < $halfSize; $i++) 
{
    $j = $i + $halfSize;

    echo "<tr><td>" . $values[$i]  . "</td>";

    // If $size is odd, $halfSize is rounded up. This means that if we have 
    // 3 elements, it will try to access to $values[3], since $halfSize would
    // be 2. The last second column element should be blank in this case.
    // So, if $halfSize is odd, and $i is the last element, don't print an
    // additional table cell.

    if (!($i == $halfSize - 1 && $size % 2 == 1))
        echo "<td>" . $values[$j]  . "</td>";

    echo "</tr>";
} 

?>

答案 1 :(得分:1)

一个功能

function sqlArr($sql){
  $ret = array();
  $res = mysql_query($sql) or trigger_error(mysql_error()." ".$sql);
  if ($res) {
    while($row = mysql_fetch_array($res)){
      $ret[] = $row;
    }
  }
  return $ret;
}

代码

$temp = sqlArr("SELECT value FROM table");
$data = array();
for($i=0;$i<50;$i++){
  $data[] = array($temp[$i],$temp[$i+50]);
}
unset($temp);

模板

<table border='1'>
<? foreach ($data as $i => $row): ?>
  <tr>
  <? foreach ($row as $cell): ?>
    <td><?=$cell?></td>
  <? endforeach ?>
  </tr>
<? endforeach ?>
</table>

答案 2 :(得分:0)

由于你已经编号,只需将其抽象出来:

a1  a51
a2  a52
...
a49 a99
a50 a100

完全相同
a1  a1+50
a2  a2+50
...
a50 a50+50

这使您拥有以下代码:

echo "<table>";

for($i=1; $i<=50; $i++) {
    echo "<tr><td>" . $i . "</td><td>" . ($i+50) . "</td></tr>";
}

echo "</table>";

注意:这要求您以这种方式生成表格。如果它实际上没有这样的编号,你将不得不想出另一种方法来生成我的清单2中的抽象表(只需考虑条目与其左邻居相关的索引)。

答案 3 :(得分:0)

我这样做的方法是创建两个单独的表(每个列宽一列),然后将它们包含在一个双列表中:

<?php
$list=array('a','b','c','d','e','f');
$midpoint=floor(count($list)/2);
$tableHeader='<table width="100%">';
$tableFooter='</table>';
$leftTable=$tableHeader;
$rightTable=$tableHeader;
for ($c=0; $c<$midpoint; $c++)
{
    $leftTable.='<tr><td width="100%">'.$list[$c].'</td></tr>';
}
$leftTable.=$tableFooter;
for ($c=$midpoint; $c<count($list); $c++)
{
    $rightTable.='<tr><td width="100%">'.$list[$c].'</td></tr>';
}
$rightTable.=$tableFooter;
$mainTable='<table><tr><td width="50%">'.$leftTable.'</td><td width="50%">'.$rightTable.'</td></tr></table>';
echo $mainTable;
?>

添加一些CSS来删除子表和边框周围的填充等,你应该好好去。

相关问题