2012-01-18 121 views
0

我有我想要从数据库中获取的值列表。所以列表很长我想在两列中获取列表。我怎样才能把它分成两列。例如.. 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来做到这一点。

回答

1

似乎每一次循环你重置你的结果。在时间之外设置$结果。更接受的方式来做到这一点是:

while ($row = mysql_fetch_assoc($sql)){ 


} 

然后测试$我,看它是否被2整除(这意味着你有2列,需要添加行和新的行代码开始的结束)。

if($i%2 == 0){ 
    echo '</tr><tr>'; 
} 
+0

如果我希望使用它明智的而不是逐行。我的意思是第一列的前五名和第二列的后五位? – 2012-01-18 20:04:15

+0

然后只添加就是你的$ i == 5,然后重置$ i = 0,然后重新执行。 – rncrtr 2012-01-18 20:12:27

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 } ?> 

编辑:Bug修复..

我觉得Colmn行这会工作:

<?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  
    } 
?> 
+0

如果我想用列而不是行方式。我的意思是第一列的前五名和第二列的后五位? – 2012-01-18 20:03:26

+0

比你可以使用Mysql_result($字符串,要求的数量,行的名称)获取偶数和奇数,并显示它们..在foreach循环 – Rednas 2012-01-18 20:06:08

+0

我认为我的新编辑将工作..(我希望我didn; t测试) – Rednas 2012-01-18 20:12:40

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++; } ?>