我有一个循环播放音乐曲目的数组,但是我需要从数组的最后一个元素中删除逗号,有人可以帮忙吗?
<?php foreach ($bucket_contents as $file){ $fname = $file['name']; $furl = "http://".$isdHtml5Bucket.".s3.amazonaws.com/".urlencode($fname);
if(preg_match("/\.mp3$/i", $furl)) { ?>
{
name:"<?php echo basename($fname); ?>",
mp3:"<?php echo $furl; ?>"
},
<?php }else{ ?>
{
name:"<?php echo basename($fname); ?>",
m4a:"<?php echo $furl; ?>"
},<?php } } ?>
这是数组的输出。
{
name:"bassline",
m4a:"http://suyssamuelarawaeast.s3.amazonaws.com/warehouse%2Fbassline%2F"
},
{
name:"Project Bassline - Drop The Pressure (Jack Beats Rinsed Out Remix).mp3",
mp3:"http://suyssamuelarawaeast.s3.amazonaws.com/warehouse%2Fbassline%2FProject+Bassline+-+Drop+The+Pressure+%28Jack+Beats+Rinsed+Out+Remix%29.mp3"
},
{
name:"deadmau5 vs jelo the reward is cheese.mp3",
mp3:"http://suyssamuelarawaeast.s3.amazonaws.com/warehouse%2Fdeadmau5+vs+jelo+++the+reward+is+cheese.mp3"
},
{
name:"vocal",
m4a:"http://suyssamuelarawaeast.s3.amazonaws.com/warehouse%2Fvocal%2F"
},
{
name:"Thin Ice",
free:true,
mp3:"http://www.jplayer.org/audio/mp3/Miaow-10-Thin-ice.mp3",
oga:"http://www.jplayer.org/audio/ogg/Miaow-10-Thin-ice.ogg"
},
如果滚动到数组的最后一个元素,则可以看到输出的逗号。 我真的需要从数组的最后一个元素中删除这个逗号。
由于
答案 0 :(得分:7)
将您的字符串传递给rtrim()
,并将charlist中的逗号指定为可移动字符:
$str = rtrim($str, ',');
修改强>
或......也许这种方法(未经测试):
$songs = array();
foreach ($bucket_contents as $file) {
$fname = $file['name'];
$furl = "http://".$isdHtml5Bucket.".s3.amazonaws.com/".urlencode($fname);
$type = preg_match("/\.mp3$/i", $furl) ? 'mp3' : 'm4a';
$songs[] = sprintf('{ name: %s, %s: %s }', $fname, $type, $furi);
}
echo implode(',', $songs);
答案 1 :(得分:0)
修改:清理代码。这个不使用临时数组,就像其他答案一样。
我没有看到该代码如何产生该输出,因为他的最终输出块中包含您不打印的字段。除此之外,这样的事情可能就是你想要的(未经测试):
<?php
$comma = '';
foreach ($bucket_contents as $file) {
$fname = $file['name'];
$furl = "http://".$isdHtml5Bucket.".s3.amazonaws.com/" . urlencode($fname);
$ext = preg_match("/\.mp3$/i") ? "mp3" : "m4a";
printf('%s{\nname:"%s",\n%s:"%s"\n}', $comma, $fname, $type, $furi);
$comma = ",\n";
}
?>
答案 2 :(得分:0)
<?php
foreach($bucket_contents as $file){
$fname = $file['name'];
$furl = "http://".$isdHtml5Bucket.".s3.amazonaws.com/".urlencode($fname);
$ext = preg_match("/\.mp3$/i") ? "mp3" : "m4a";
$t[] = '{name:"'.basename($fname).'",'.$ext.':"'.$furl.'"}';
}
echo implode(',',$t);
你去吧。好多了:))