[英]convert string into json data using php
我想將以下字符串轉換為json。 以下是指向圖像的鏈接,然后是定界符“,”,然后是鏈接,然后是定界符“,”,然后是標題和副標題之間的另一個定界符“,”,然后是另一個定界符“#”。
$str = "http://example.com/1.jpg,http://example.com/1.html,title,subtitle#http://example.com/2.jpg,http://example.com/2.html,title,subtitle#http://example.com/3.jpg,http://example.com/3.html,title,subtitle";
我希望上面的字符串看起來像以下
[
{
image: http://example.com/1.jpg,
link: http://example.com/1.html,
title: title,
subtitle: subtitle
},
{
image: http://example.com/2.jpg,
link: http://example.com/2.html,
title: title,
subtitle: subtitle
},
{
image: http://example.com/3.jpg,
link: http://example.com/3.html,
title: title,
subtitle: subtitle
}
]
如何在php中實現以上目標?
// first split the string on the '#' delimiter
$list = explode("#", $str);
// create output array, will be used as input for json_encode function
$outputArray = array();
// go through all the lines found when string was splitted on the '#' delimiter
foreach ($list as $line)
{
// split the single line in to four part,
// using the ',' delimiter
list($image, $link, $title, $subtitle) = explode(',', $line);
// store everything in the output array
$outputArray[] = array(
'image' => $image,
'link' => $link,
'title' => $title,
'subtitle' => $subtitle,
);
}
// parse the array through json_encode and display the output
echo json_encode($outputArray);
你可以這樣做:
$str = "http://example.com/1.jpg,http://example.com/1.html,title,subtitle#http://example.com/2.jpg,http://example.com/2.html,title,subtitle#http://example.com/3.jpg,http://example.com/3.html,title,subtitle";
$keys = Array("image", "link", "title", "subtitle");
$o = Array();
foreach(explode("#", $str) as $value) {
$new = Array();
foreach(explode(",", $value) as $key => $sub){
$new[ $keys[ $key ] ] = $sub;
}
$o[] = $new;
}
echo json_encode($o);
輸出:
[
{
"image":"http:\/\/example.com\/1.jpg",
"link":"http:\/\/example.com\/1.html",
"title":"title",
"subtitle":"subtitle"
},
{
"image":"http:\/\/example.com\/2.jpg",
"link":"http:\/\/example.com\/2.html",
"title":"title",
"subtitle":"subtitle"
},
{
"image":"http:\/\/example.com\/3.jpg",
"link":"http:\/\/example.com\/3.html",
"title":"title",
"subtitle":"subtitle"
}
]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.