Remove last comma or prevent it from being printed at all MySQL/PHP

匿名 (未验证) 提交于 2019-12-03 02:38:01

问题:

I am printing a set of words that is placed in a MySQL database and I am retrieving it with PHP. I want to present it as a comma separated list, but I need it not to print or remove the last comma. How could I do this?

I did try to use rtrim, but I did not probably do it right. This is my code as it is today:

<?php  $query0  = "SELECT LCASE(ord) FROM `keywords` ORDER BY RAND()"; $result0 = mysql_query($query0);  while($row0 = mysql_fetch_array($result0, MYSQL_ASSOC)) { $keyword = $row0['LCASE(ord)'];  echo "$keyword, "; ?> 

I did try to use rtrim, my attempt was something like this (I might be honest enough to say that I am in above my head in this ;) )

$keyword = $row0['LCASE(ord)']; $keywordc = "$keyword, "; $keyword- = rtrim($keywordc, ', '); echo "$keyword-, "; 

As you might imagine, this did not print much (but at least it did not leave me with a blank page...)

回答1:

I usually do this by placing the results in an array first

$some_array = array(); while($row0 = mysql_fetch_array($result0, MYSQL_ASSOC)) {    $some_array[] = $row0['LCASE(ord)']; } 

then simply:

echo "My List: " . implode(', ', $some_array); // Output looks something like: My List: ord1, ord2, ord3, ord4 


回答2:

I would do:

$keywords = array(); while($row0 = mysql_fetch_array($result0, MYSQL_ASSOC)) {    $keywords[] = $row0['LCASE(ord)']; }  echo implode(',', $keywords); 


回答3:

substr($string, 0, -1); 

That removes the last character.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!