在执行基本查询时,我已经阅读了很多方法来删除字符串末尾的逗号,但基本的东西似乎都没有使用这个特定的脚本。希望我只是在想这个。我的脚本通过数据库并将城市置于正确的状态,但我需要删除最后一个城市逗号。
这是我正在使用的脚本
<?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
}
}
?>
答案 0 :(得分:6)
另一种在这种情况下效果很好的替代方法是创建一个字符串并简单地修剪掉最后一个逗号。
foreach ($market_cities as $cityId => $cityInfo) {
$citystr .= $cityInfo['market_cities']. ',';
}
echo rtrim($citystr, ',');
答案 1 :(得分:1)
我认为最干净的方法就是这样做......
$data = array_map(function($item) { return $item['market_cities']; }, $market_cities);
$output = implode(',', $data);
答案 2 :(得分:1)
您还可以使用join函数从数组中输出以逗号分隔的列表。所以而不是:
foreach ($market_cities as $cityId => $cityInfo) {
echo $cityInfo['market_cities']. ',';
...
...
}
看起来像是:
$cities = join(",", $market_cities);
echo $cities;
答案 3 :(得分:0)
如果你不需要这个“cityId”,你也可以让mysql完成工作:
<?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;
}
答案 4 :(得分:-1)
echo $cityInfo['market_cities'];
if(count($market_cities)<$i) {
echo ",";
}
最简单的方法。