2012-07-15 36 views
0

我測試了這個在Firefox上,它工作正常,但在IE瀏覽器它不工作,因爲在數組的最後部分逗號。現在我怎樣才能刪除逗號使用PHP?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 
} 
?> 
+0

,去年逗號正在成爲「噩夢」,用一個計數器,並增加每一個循環,如果計數器的值等於計數($圖像),然後跳過打印逗號。 – Gntem 2012-07-15 09:42:14

回答

6

你不需要手工編寫自己的JSON。使用json_encode()

echo json_encode($images); 

要儘管如此回答這個問題,有兩種方式避免後面的逗號(這確實應該被刪除,即使火狐等人讓你逃脫它)

1 - conditionlise其輸出在您的循環中

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

注意這隻適用於索引數組。對於關聯的,你必須設置你自己的計數器變量(因爲$key不會是一個數字)。

2 - 之後將其除去,例如,與正則表達式

$str = "apple, pear, orange, "; 
$str = preg_replace('/, ?$/', '', $str); 
+0

謝謝,我知道了 – mapet 2012-07-15 09:49:37

1

Upvoted 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 
    } 
} 
+0

有趣 - 請在可能的情況下展示如何在您的答案 – Utkanos 2012-07-15 09:50:19

+0

@Utkanos更新:) – Martin 2012-07-15 09:51:51

1

不要寫你自己的JSON,使用json_encode

<?php 

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

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

?> 

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