这是我的 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++;
}
(我在 <script> 中运行这个 php 片段,这就是为什么我需要一个“,”最后排除最后一项)
我们将不胜感激。
最佳答案
您的代码中似乎遗漏了一个“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++;
}
关于php - while循环与foreach,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29570983/