2011-10-03 108 views
-2

渲染我有以下代碼:防止最後分隔字符循環

if(hasRows($resultC)){ 
    while($row = mysql_fetch_row($resultC)) { 
     $mescategories = '<span><a href="' . CalRoot . 
      '/index.php?com=searchresult&amp;t=' . $row[0] . 
      '" rel="tag" class="eventMain">' . cOut($row[1]) . '</a></span> | ' ; 
     echo $mescategories; 
    }//end while 
}//end if 

渲染輸出的樣子:

cat 1 | cat 2 | cat 3 | cat 4 |

如何防止最後|字符被渲染。

+2

你應該看看使用implode。 – checkenginelight

+0

好吧,就這樣做...! –

回答

5
$catArray = array(); 
if(hasRows($resultC)){ 
    while($row = mysql_fetch_row($resultC)){ 
     array_push($catArray, '<span><a href="' . CalRoot . '/index.php?com=searchresult&amp;t=' . $row[0] . '" rel="tag" class="eventMain">' . cOut($row[1]) . '</a></span>'); 
    }//end while 
    echo implode('|', $catArray); 
}//end if 
+0

不應該在「內部」字符串碎片之前「膠水」? http://php.net/manual/en/function.implode.php – n00dle

+0

我認爲你是正確的,但我引用了O'Reilly Cuckoo的書,它反過來了。我會編輯。 –

+1

啊,看看在線說明中的說明。他們可以以任何順序。 –

2
$i = 0; //set before while loop 
$i++; //inserted into while loop 
if ($i != mysql_num_rows($resultC)) { //inserted into while loop 
    $mescategories .= " | " ; 
} 

mysql_num_rows會告訴查詢中有多少行,然後會爲除最後一行之外的每行添加管道字符。

編輯:我認爲$ i ++實際上應該在if語句之前。

+0

這是非常令人困惑的,因爲你的答案中有一個單獨的代碼塊,由單獨的代碼片段組成,它們將在不同的地方出現。 –

2

如何放置條件語句。計算行的大小,如果$ count = $ maxcount那麼不要回顯「|」字符。

1

我還沒有檢查過你的格式。剛剛添加了「第一個」變量。

if(hasRows($resultC)){ 
    $first = true; 
    while($row = mysql_fetch_row($resultC)){ 
     $mescategories = ' '.($first ? "":"|").' <span><a href="' . CalRoot . '/index.php?com=searchresult&amp;t=' . $row[0] . '" rel="tag" class="eventMain">' . cOut($row[1]) . '</a></span> ' ; 
     echo $mescategories; 
     $first = false; 
    }//end while 
}//end if 
+0

什麼是'''.'? –

+0

給變量增加一個空格 –

+0

呵呵,沒錯。我認爲它是'''。' –

3

你可以指望使用mysql_num_rows($resultC)的行數,並且對你的循環的計數器。或者,我會做的方式是一樣的東西:

if(hasRows($resultC)){ 
    // Create an empty array 
    $links = array(); 

    while($row = mysql_fetch_row($resultC)){ 
     // Add each text link to the array 
     $links[] = '<span><a href="' . CalRoot . '/index.php?com=searchresult&amp;t=' . $row[0] . '" rel="tag" class="eventMain">' . cOut($row[1]) . '</a></span>' ;  
    } 
    // "Glue" the array back together using implode, with the separator between each. 
    echo implode(' | ', $links); 
} 
1

嘗試

if(hasRows($resultC)){ 
$i=0; 
while($row = mysql_fetch_row($resultC)){ 
    $spaceline =($i>0) ? '|' : ''; 
    $mescategories = '<span><a href="' . CalRoot . '/index.php?com=searchresult&amp;t=' . $row[0] . '" rel="tag" class="eventMain">' . cOut($row[1]) . '</a></span>' ; 
    $i++; 
    echo $spaceline.$mescategories; 

    }//end while 
}//end if 
0

只是做

echo substr($mescategories, 0, -1);

,而不是echo $mescategories 你讓它把|每一個實例後,然後刪除最後一個字符

否則,如果你需要知道你使用數組的最後一個關鍵:

end($array); 
$lastKey = key($array); 

但不要忘記重置你用它做的事情之前

reset($array);