从字符串高级结束中删除逗号

从字符串高级结束中删除逗号

问题描述:

I have read plenty of ways of removing the comma at the end of a string when doing basic queries but none of the basic stuff seems to be working with this particular script. Hopefully I'm just over thinking this. My script goes through the database and places the cities under the proper states but I need the last cities comma to be removed.

Here is the script I am using

<?php
$sql = "SELECT * FROM markets WHERE id = 0 ORDER BY market_state";
$res = mysql_query($sql);
$list = array();
while ($r = mysql_fetch_object($res)) {
 $list[$r->market_state][$r->id]['market_cities'] = $r->market_cities;

}

foreach ($list as $market_state => $market_cities) {
echo '<h1>' . $market_state . '</h1>';

foreach ($market_cities as $cityId => $cityInfo) {
echo $cityInfo['market_cities']. ',';

// etc
}

}
?>

You can also let mysql make the work if you don't need this "cityId":

<?php
$sql = "SELECT market_state,GROUP_CONCAT(market_cities) as market_cities FROM markets WHERE id = 0 GROUP BY market_state ORDER BY market_state";
$res = mysql_query($sql);
$list = array();
while ($r = mysql_fetch_object($res)) {
    $list[$r->market_state] = $r->market_cities;
}

foreach ($list as $market_state => $market_cities) {
    echo '<h1>' . $market_state . '</h1>';
    echo $market_cities;
}

echo $cityInfo['market_cities'];
if(count($market_cities)<$i) {
    echo ",";
}

The simplest way of doing it.

Another alternative that works really well in this situation, is to make a string and simply trim off the last comma.

foreach ($market_cities as $cityId => $cityInfo) {
  $citystr .= $cityInfo['market_cities']. ',';
}
echo rtrim($citystr, ',');

I think the cleanest way is to do this...

$data = array_map(function($item) { return $item['market_cities']; }, $market_cities);
$output = implode(',', $data);

You could also use the join function to output a comma-separated list from an array. So instead of:

foreach ($market_cities as $cityId => $cityInfo) {
    echo $cityInfo['market_cities']. ',';
    ...
    ...
}

It would look something like:

$cities = join(",", $market_cities);
echo $cities;