2014-11-17 88 views
-1

我喜欢从PHP可变删除最后一个逗号(输出)

<?php 
    $query=mysql_query("SELECT * FROM visited_city WHERE username='$user' LIMIT 3");  

    while($row=mysql_fetch_assoc($query)){ 
    $city=$row['city']; 

    echo '<a href="'.$city.'">'.$city.', </a>'; 
    } 
?> 

结果PHP变量=

达卡,德里,孟买,

事实上,我想像

达卡,德里,孟买

对不起,有这么多的答案,我发现,但不匹配米è...

+0

入住这http://stackoverflow.com/questions/5592994/remove-last-character-from-string – Naincy

+0

纳尼西古普塔,在这种情况下,字符串已经被输出。因此,你的链接不起作用。 –

+0

@Naincy Gupta,我试过了,这让我在这里问你的帮助...... –

回答

1

假设城市名单是一个数组$城市则

<?php 
$counter = 0; 

// the list of cities to be printed 
$list = ""; 

foreach($cities as $city) { 
    if($counter == count($cities)) { 
     $list.= $city; 
    } else { 
     $list.= $city.","; 
    } 
     $counter++; 
} 

echo $list; 
?> 
+1

是的,这个工作,但它只是最令人费解的代码来做到这一点。 – deceze

+0

@Mohammad Attat,兄弟,我的代码处于一个while循环中。运行您建议的代码后,显示错误消息“为foreach()提供的无效参数”。希望你会回复我。 –

+0

@AbuBakkarSiddique你能告诉我包括while循环的代码吗? –