0

好吧,在你说什么之前,我已经做了一个小时的研究,没有任何技术在起作用......继续这个问题:

我正在使用一个多维数组,并试图在一个数组中回显一个特定品牌的所有汽车模型。我有以下代码:

<?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 功能,但这对我不起作用。还尝试了内爆功能,但没有成功。我可以在这里帮忙吗?非常感谢您的时间!谢谢。

4

2 回答 2

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']);
?>
于 2013-09-11T16:57:12.400 回答
0

我认为这是你真正想要的:

foreach($cars['Toyota'] as $key=>$x)
{
echo $x;
if($cars['Toyota'][$key+1]){echo ', ';}
}
于 2013-09-11T17:02:02.727 回答