while循环与foreach

while loop with foreach

这是我的 while 循环。

$getsongs = mysql_query("SELECT * FROM hth_songs WHERE album='$album'");
while($song = mysql_fetch_array($getsongs)){
?>
    { title:"<?php echo $song[title]; ?>" },

<?php } ?>

问题是我总是需要在 echo 的末尾有一个“,”。但如果它是最后一项,我不想要最后的“,”。

我已经查过了,我需要做这样的事情,但我无法让它工作,也不知道该怎么做。

$i = 0;
$len = count($array);
foreach ($array as $item) {
   if ($i == 0) {
    { title:"<?php echo $song[title]; ?>" }, // first
   } else if ($i == $len - 1) {
    { title:"<?php echo $song[title]; ?>" } // last
   }
    { title:"<?php echo $song[title]; ?>" }, // …
$i++;
}

(我 运行 这个 php 片段在 < script> 中,这就是为什么我需要一个“,” 最后排除最后一项)

我们将不胜感激。

从数组中的值获取逗号分隔字符串的最简单方法是使用 implode()。

$array = array('lastname', 'email', 'phone');
$comma_separated = implode(",", $array);

echo $comma_separated; // lastname,email,phone

请注意,没有尾随逗号,因为逗号是将值组合在一起的 "glue"。

你的代码没有意义,$song设置在哪里?为什么在 if 块中使用额外的花括号?

假设您可以适应您的情况:

$string = '';
foreach ($array as $item) {
    $string .= $item['song'] . ',';
}
echo rtrim($string, ',');

您的代码中似乎遗漏了一个 'else':

$i = 0;
$len = count($array);
foreach ($array as $item) {
   if ($i == 0) {
    { title:"<?php echo $song[title]; ?>" }, // first
   } else if ($i == $len - 1) {
    { title:"<?php echo $song[title]; ?>" } // last
   }
   else
    { title:"<?php echo $song[title]; ?>" }, // …
$i++;
}

你的标题好像太多了。试试这个:

$i = 0;
$len = count($array);
foreach ($array as $item) {
   $i++;
   if ($i == $len) {
      { title:"<?php echo $song[title]; ?>" } // last
   } else {
      { title:"<?php echo $song[title]; ?>" }, // others
   }     
}