好的,在你说什么之前,我已经做了一个小时的研究,没有任何技术工作......继续问题:
我正在使用多维数组并试图回显数组中某个特定品牌的所有汽车模型。我有以下代码:
<?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>";
foreach($cars['Toyota'] as $x)
{
$cars['Toyota'] = rtrim($x, ',');
echo "$x, ";
}
?>
显然,我最近的一次拍摄是使用rtrim功能,但这对我不起作用。还试过内爆功能没有成功。我可以在这里帮忙吗?非常感谢您的时间!感谢。
答案 0 :(得分:2)
你的问题是你自己将尾随逗号放在那里。尝试这样的事情:
<?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']);
?>
答案 1 :(得分:0)
我认为这是你真正想要的:
foreach($cars['Toyota'] as $key=>$x)
{
echo $x;
if($cars['Toyota'][$key+1]){echo ', ';}
}