我在firefox上测试了它并且它工作正常,但在IE中它不起作用,因为在数组的最后部分使用逗号.现在如何使用php删除逗号?
实际结果:
{image : 'folder/pic1.jpg', title : '', thumb : 'folder/pic1.jpg', url : ''},
{image : 'folder/pic2.jpg', title : '', thumb : 'folder/pic2.jpg', url : ''},
{image : 'folder/pic3.jpg', title : '', thumb : 'folder/pic3.jpg', url : ''},
Run Code Online (Sandbox Code Playgroud)
预期结果:
{image : 'folder/pic1.jpg', title : '', thumb : 'folder/pic1.jpg', url : ''},
{image : 'folder/pic2.jpg', title : '', thumb : 'folder/pic2.jpg', url : ''},
{image : 'folder/pic3.jpg', title : '', thumb : 'folder/pic3.jpg', url : ''}
Run Code Online (Sandbox Code Playgroud)
码:
<?php
$directory = "pic/";
$images = glob("".$directory."{*.jpg,*.JPG,*.PNG,*.png}", GLOB_BRACE);
if ($images != false)
{
?>
<script type="text/javascript">
jQuery(function($){
$.supersized({
slideshow: 1,//Slideshow on/off
autoplay: 1,//Slideshow starts playing automatically
start_slide: 1,//Start slide (0 is random)
stop_loop: 0,
slides: [// Slideshow Images
<?php
foreach( $images as $key => $value){
echo "{image : '$value', title : '', thumb : '$value', url : ''},";
}
?>
],
progress_bar: 1,// Timer for each slide
mouse_scrub: 0
</script>
<?php
}
?>
Run Code Online (Sandbox Code Playgroud)
您不需要手动编写自己的JSON代码.使用json_encode()
echo json_encode($images);
Run Code Online (Sandbox Code Playgroud)
尽管如此,为了回答这个问题,有两种方法可以避免使用尾随逗号(即使Firefox等人让你侥幸逃脱,也应该删除它)
1 - 在循环中条件化其输出
$arr = array('apple', 'pear', 'orange');
foreach($arr as $key => $fruit) {
echo $fruit;
if ($key < count($arr) - 1) echo ', ';
}
Run Code Online (Sandbox Code Playgroud)
请注意,这仅适用于索引数组.对于关联变量,你必须设置自己的计数器变量(因为它$key不是数字).
2 - 之后将其删除,例如使用REGEX
$str = "apple, pear, orange, ";
$str = preg_replace('/, ?$/', '', $str);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
214 次 |
| 最近记录: |