你的问题是你自己把尾随的逗号放在那里。尝试这样的事情:
<?php
$cars = array(
"Dodge" => array("Avenger","Challenger","Charger","Dart"),
"Toyota" => array("Highlander","Tundra","Corolla"),
"Nissan" => array("Sentra","Altima","Maxima")
);
echo "Make: Toyota";
echo "<br><br>";
$first = TRUE;
$carString = '';
foreach($cars['Toyota'] as $x){
if ($first){
$carString .= $x;
$first = FALSE;
}else{
$carString .= ", $x";
}
}
echo $carString;
?>
如果你想要一个更简单的循环,没有控制结构(我觉得演示循环中真正发生的事情很有用),那么你可以rtrim
在循环之后使用,如下所示:
<?php
$cars = array(
"Dodge" => array("Avenger","Challenger","Charger","Dart"),
"Toyota" => array("Highlander","Tundra","Corolla"),
"Nissan" => array("Sentra","Altima","Maxima")
);
echo "Make: Toyota";
echo "<br><br>";
$carString = '';
foreach($cars['Toyota'] as $car) {
$carString .= $car.',';
}
echo rtrim($carString, ',');
?>
如果除了构建字符串之外你不需要循环任何东西,你可以只implode
用数组来打印它:
<?php
$cars = array(
"Dodge" => array("Avenger","Challenger","Charger","Dart"),
"Toyota" => array("Highlander","Tundra","Corolla"),
"Nissan" => array("Sentra","Altima","Maxima")
);
echo "Make: Toyota";
echo "<br><br>";
echo implode(', ', $cars['Toyota']);
?>