簡體   English   中英

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);

贊成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
  }
}

不要編寫自己的JSON,請使用json_encode

<?php

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

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

?>

$.supersized(<?php echo json_encode($data); ?>);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM