2015-05-20 87 views
1

我的選擇查詢是這樣的,在group_name中我給逗號但我想從最後刪除逗號。我已經嘗試過修剪,但是它刪除了所有的逗號,並且我只想刪除最後一個逗號。在array從while循環中的字符串中刪除最後一個逗號

$selctGroup = "SELECT contact_id,group_name FROM contact_group 
         LEFT JOIN `group` ON `group`.`group_id` = `contact_group`.`group_id` 
       WHERE contact_id = ".$row['contact_id']; 
$selctGroupRes = mysql_query($selctGroup); 
while($groupRow = mysql_fetch_array($selctGroupRes)) 
{ 
    echo $groupRow['group_name'].','; 
} 
+0

嘗試使用'RTRIM();' –

+0

不靈@玉萍 –

+0

檢查答案在這裏:。http://stackoverflow.com/questions/5592994/remove-the-last-character-from -string – ErdraugPl

回答

3

而不是呼應了每一行,建立一個字符串在最後回顯。在此之前,用rtrim($str,",")從最後刪除逗號逗號。

$str = ""; 
while($groupRow = mysql_fetch_array($selctGroupRes)) { 
    $str .= $groupRow['group_name'].','; 
} 
echo rtrim($str,","); 
+1

更簡單的解決方案... – Makesh

0

存儲數據,並使用implode你可以刪除最後一個逗號

while($groupRow = mysql_fetch_array($selctGroupRes)) 
{ 
    $result[] = $groupRow['group_name']; 
} 

echo implode(",", $result); 
+0

與此輸出是這樣的測試,測試2,,測試3,測試4, –

+0

不要在循環內附加逗號 – Makesh

+0

@PrashantBhatt現在編輯我的代碼嘗試 – Saty

0

使用RTRIM()。像下面

​​
+0

不工作@Prasad –

+0

應該是'rtrim($ groupRow ['group_name'],「,」);'你的代碼只會刪除字符串右邊的空白 – roullie

+0

得到了解決方案嗎? – Prasad

1
$selctGroup = "SELECT contact_id,group_name FROM contact_group 
         LEFT JOIN `group` ON `group`.`group_id` = `contact_group`.`group_id` 
       WHERE contact_id = ".$row['contact_id']; 
$selctGroupRes = mysql_query($selctGroup); 
$str=''; 
while($groupRow = mysql_fetch_array($selctGroupRes)) 
{ 
    if($str=='') 
     $str=$groupRow['group_name']; 
    else 
     $str.=','.$groupRow['group_name']; 
} 
echo $str; 
相關問題