我有一个while循环用于编写列表。我希望每个元素之间用逗号分隔,但在最后一个元素后面写一个点,而不是一个逗号。这是我的代码
$exec = mysql_query($req);
while ($row = mysql_fetch_assoc($exec)){
echo '<strong>'.$row['name'].'</strong>, ';
}
但是我不知道怎么做。我尝试使用count()或end(),但这些都不起作用。
$html = array();
$exec = mysql_query($req);
while ($row = mysql_fetch_assoc($exec)){
$html[] = '<strong>' . htmlspecialchars($row['name']) . '</strong>';
// --------------------^^^^^^^^^^^^^^^^! (1)
}
$html = implode(', ', $html) . '.';
(1) - 永远不要在没有正确转义的情况下输出数据到HTML。
我喜欢使用内爆函数:)
$list = array();
$exec = mysql_query($req);
while ($row = mysql_fetch_assoc($exec)){
$list[] = '<strong>'.$row['name'].'</strong>';
}
$string = implode(", " , $list);
echo $string . ".";
HTH
试试这个:
$exec = mysql_query($req);
$output = array();
while ($row = mysql_fetch_assoc($exec)){
$output[] = '<strong>'.$row['name'].'</strong>';
}
echo implode(',', $output), '.';
构建字符串但不输出。然后,修剪命令并添加一个句号:
$exec = mysql_query($req);
$output = "";
while ($row = mysql_fetch_assoc($exec))
{
$output .= '<strong>'.htmlentities($row['name']).'</strong>, ';
}
if($output) echo rtrim($output, ', ').".";