2012-01-18 100 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++; } ?>