每个Php如何删除字符


Php for each how to remove characters

我在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
}
?>

您不需要手工编写自己的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);

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

<?php
$data = array(
    'slideshow' => 1,
    ...
);
foreach ($images ...) {
    $data['slides'][] = array('image' => ...);
}
?>
$.supersized(<?php echo json_encode($data); ?>);

投票支持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
  }
}