使用php将字符串转换为json数据

I want to convert following string into json. Following has a link to image then delimiter ',' then a link then a delimiter ',' then has another delimiter ',' between title and subtitle then another delimiter '#'.

$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";

I want above string to appear like following

[
    {
        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
    }
]

How can I achieve above in 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);

You can do this:

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

Output:

 [
   {
      "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"
   }
]