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

时间:2014-03-02 14:36:35

标签: 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中实现上述目标?

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:2)

你可以这样做:

$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"
   }
]