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'}
答案 0 :(得分:2)
答案 1 :(得分: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);
答案 2 :(得分: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。
答案 3 :(得分: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'}