我如何将php数组转换为json格式

时间:2015-12-26 09:28:27

标签: php arrays json

你好,例如我有json格式。我需要生成一个php数组来从那个

构建这个json
{
"posts":
    [
    {
    "detial" : {
        "titel": "web design",
        "date-publish" : "2015-02-08",
        "pic-thumbnail" : "small-web-desing-jpg",
        "pic-medium" : "medium-web-desing-jpg"
    },
    "content" : {
        "description" : "description web design post",
        "content" : "web design is modern technology in world"
    }
    }
    ]
}

请显示PHP数组构建此json的示例

2 个答案:

答案 0 :(得分:1)

很容易

只需使用PHP的json_decode()函数即可实现。

最后,将json_encode()返回数组保存到变量中。

<强>输出:

Array
(
    [posts] => Array
        (
            [0] => Array
                (
                    [detial] => Array
                        (
                            [titel] => web design
                            [date-publish] => 2015-02-08
                            [pic-thumbnail] => small-web-desing-jpg
                            [pic-medium] => medium-web-desing-jpg
                        )

                    [content] => Array
                        (
                            [description] => description web design post
                            [content] => web design is modern technology in world
                        )

                )

        )

)

PHP代码:

$results = json_decode('{

  "posts": [{

    "detial" : {

      "titel": "web design",
        "date-publish" : "2015-02-08",
        "pic-thumbnail" : "small-web-desing-jpg",
        "pic-medium" : "medium-web-desing-jpg"

    },

    "content" : {

      "description" : "description web design post",
      "content" : "web design is modern technology in world"

    }

  }]

}', true);

echo "<pre>".print_r($results, true)."</pre>";

答案 1 :(得分:0)

使用PHP函数json_decode()生成php数组。

$jsonData = json_decode('{
 "posts": [{ 

   "detial" : {

     "titel": "web design",

       "date-publish" : "2015-02-08",
       "pic-thumbnail" : "small-web-desing-jpg",
       "pic-medium" : "medium-web-desing-jpg"

   },
   "content" : {

       "description" : "description web design post",
       "content" : "web design is modern technology in world"

   }

 }]
 }',true);

 echo "<pre>";
 print_r($jsonData);  
相关问题