0

我在 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 : ''},

预期结果:

{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 : ''}

代码:

<?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
}
?>
4

3 回答 3

6

您无需手动编写自己的 JSON。采用json_encode()

echo json_encode($images);

尽管如此,要回答这个问题,有两种方法可以避免尾随逗号(它确实应该被删除,即使 Firefox 等让你侥幸逃脱)

1 - 在你的循环中条件化它的输出

$arr = array('apple', 'pear', 'orange');
foreach($arr as $key => $fruit) {
    echo $fruit;
    if ($key < count($arr) - 1) echo ', ';
}

请注意,这仅适用于索引数组。对于关联的,您必须设置自己的计数器变量(因为$key不会是数字)。

2 - 之后删除它,例如使用 REGEX

$str = "apple, pear, orange, ";
$str = preg_replace('/, ?$/', '', $str);
于 2012-07-15T09:42:34.180 回答
1

支持 Utkanos 的使用答案,json_encode但为了让您的代码正常工作,您可以使用它end来比较您的值是否相同,或key验证密钥。

foreach ($array as $key => $value) { 
  if ($value == end($array)) {
      // Last element by value
  }

  end($array);
  if ($key == key($array)) {
      // Last element by key
  }
}
于 2012-07-15T09:47:14.777 回答
1

不要编写自己的 JSON,请使用json_encode

<?php

$data = array(
    'slideshow' => 1,
    ...
);

foreach ($images ...) {
    $data['slides'][] = array('image' => ...);
}

?>

$.supersized(<?php echo json_encode($data); ?>);
于 2012-07-15T09:51:38.947 回答