2013-11-26 120 views
0

PHP從最後一個數組值刪除逗號

$meta = get_post_custom($post->ID); 
$images = $meta['img1'][0]; // urls separated with comma 
$images = explode(',', $images); 
foreach ($images as $image) { 
    echo '{image : '.$image.', title : "Credit: x"},'; 
}; 

輸出

{image : 'http://localhost/slideshow/1.jpg', title : 'Credit: x'}, 
{image : 'http://localhost/slideshow/2.jpg', title : 'Credit: x'}, 
{image : 'http://localhost/slideshow/3.jpg', title : 'Credit: x'}, 
{image : 'http://localhost/slideshow/4.jpg', title : 'Credit: x'}, // last comma, just after } 

我想刪除最後一個評論逗號中輸出。

這正是我試圖得到:

所需的輸出

{image : 'http://localhost/slideshow/1.jpg', title : 'Credit: x'}, 
{image : 'http://localhost/slideshow/2.jpg', title : 'Credit: x'}, 
{image : 'http://localhost/slideshow/3.jpg', title : 'Credit: x'}, 
{image : 'http://localhost/slideshow/4.jpg', title : 'Credit: x'} 
+2

收益如何在PHP函數使用構建生成有效的JSON? (json_encode) –

回答

2

你有很多的選擇:

// Using rtrim 
$meta = get_post_custom($post->ID); 
$images = $meta['img1'][0]; // urls separated with comma 
$images = explode(',', $images); 
$string = ''; 
foreach ($images as $image) { 
    $string .= '{image : '.$image.', title : "Credit: x"},'; 
}; 
$string = rtrim($string, ','); 
echo $string; 

// Using substring 
$meta = get_post_custom($post->ID); 
$images = $meta['img1'][0]; // urls separated with comma 
$images = explode(',', $images); 
$string = ''; 
foreach ($images as $image) { 
    $string .= '{image : '.$image.', title : "Credit: x"},'; 
}; 
$string = substr($string, 0, -1); 
echo $string; 

// Using implode 
$meta = get_post_custom($post->ID); 
$images = $meta['img1'][0]; // urls separated with comma 
$images = explode(',', $images); 
$stringElements = array(); 
foreach ($images as $image) { 
    stringElements[] = '{image : '.$image.', title : "Credit: x"}'; 
}; 

$string = implode(',', $stringElements); 
echo $string; 

還要考慮使用一種更有效的方式來創建JSON字符串:json_encode

+0

這已經足夠了。 我接受答案;)謝謝! –

2

可以緩衝輸出到變量和解決這樣:

echo rtrim($bufferedData, ','); 

但正如我所看到的,最好使用json functions

+0

感謝您的時間! –

2

所以你所有的代碼都是關於從你的數據創建JSON的。這將是:

$data = 'http://localhost/slideshow/1.jpg,http://localhost/slideshow/2.jpg,http://localhost/slideshow/3.jpg'; 
$credit = 'x'; 
$result = json_encode(array_map(function($image) use ($credit) 
{ 
    return ['image'=>$image, 'Credit'=>$credit]; 
}, explode(',', $data))); 
//var_dump($result); 
+0

感謝您的時間! –

1

這也許使用RTRIM()

$images = 'image1.png,image2.png,image3.png'; 
$ex = explode(',', $images); 
foreach ($ex as $image) { 
    $image_string .= "{'image' : '{$image}', 'title' : 'Credit: x'},"; 
} 

print rtrim($image_string, ','); 

以上低於

{'image' : 'image1.png', 'title' : 'Credit: x'}, 
{'image' : 'image2.png', 'title' : 'Credit: x'}, 
{'image' : 'image3.png', 'title' : 'Credit: x'} 
+0

感謝您的時間! –