我有要从数据库中获取的值列表。所以List很长我想在两列中获取列表。我怎么能在2列中打破它。例如..
列出aphabets
A | B
C | D
E | F
G | H
I | J
K | L
这样。我使用了以下方法......
<?php
$sql = mysql_query("SELECT * FROM poet WHERE status='Publish' ORDER BY name ") or die(mysql_error());
$total_rows = mysql_num_rows($sql);
$i = 1;
$j = ceil($total_rows/2);
while ( $i <= $j ) {
$result = mysql_fetch_assoc($sql);
?>
<tr>
<? if($i%2 == 0) { ?>
<td class="navigation"><?php echo fetch_table_poet( $result["pid"], 1, 3); ?></td>
<? } elseif($i%2 != 0) { ?>
<td class="navigation"><?php echo fetch_table_poet( $result["pid"], 1, 3); ?></td>
<? } ?>
</tr>
<?php $i++; } ?>
它以这种方式给我输出..
A | A
B | B
C | C
注意 - 我希望使用PHP而不使用任何jquery或javascript。
答案 0 :(得分:1)
每次循环时,您似乎都在重置结果。在结果之外设置$ results。更容易接受的方法是:
while ($row = mysql_fetch_assoc($sql)){
}
然后测试$ i以查看它是否可被2整除(意味着你有2列,需要添加行的结尾和新行标记的开头)。
if($i%2 == 0){
echo '</tr><tr>';
}
答案 1 :(得分:1)
尝试:
<?php
$sql = mysql_query("SELECT * FROM poet WHERE status='Publish' ORDER BY name ") or die(mysql_error());
$i = 0;
$total_rows = mysql_num_rows($sql);
while ( $result = mysql_fetch_assoc($sql) ) {
$i++;
?>
<? if($i&1 == 1) { ?>
<tr>
<td class="navigation"><?php echo $result["pid"]; ?></td>
<? } elseif($i&1 == 0) { ?>
<td class="navigation"><?php echo $result["pid"]; ?></td>
</tr>
<? }
if($i == $total_rows && $total_rows&1 == 1){ echo "</tr>"; } ?>
<?php } ?>
编辑:错误修复..
我认为列行可行:
<?php
$sql = mysql_query("SELECT * FROM poet WHERE status='Publish' ORDER BY name ") or die(mysql_error());
$total_rows = mysql_num_rows($sql);
$iOne = 1;
$iTwo = floor($totalRows/2);
foreach($iOne=1,$iTwo=ceil($totalRows/2); $iTwo < $total_rows; $iOne++,$iTwo++){
?>
<tr>
<td class="navigation"><?php echo mysql_result($sql,$iOne,'pid') ?></td>
<td class="navigation"><?php echo mysql_result($sql,$iTwo,'pid') ?></td>
</tr>
<?php
}
?>
答案 2 :(得分:0)
我建议使用jQuery columnizer作为解决问题的方法http://welcome.totheinter.net/columnizer-jquery-plugin/
答案 3 :(得分:0)
最后,我成功完成了代码。
<?php
$sql = mysql_query("SELECT * FROM poet WHERE status='Publish' ORDER BY name ") or die(mysql_error());
$total_rows = mysql_num_rows($sql);
$i = 1;
while ( $result = mysql_fetch_assoc($sql) ) { ?>
<?php if($i%2 == '1') { ?>
<tr>
<td class="navigation"><?php echo fetch_table_poet( $result["pid"], 1, 3); ?></td>
<?php } elseif($i%2 == '0') { ?>
<td class="navigation"><?php echo fetch_table_poet( $result["pid"], 1, 3); ?></td>
</tr>
<?php } ?>
<?php $i++; } ?>