Titanium,PHP和json编码

时间:2013-12-19 09:16:06

标签: php json

我正在尝试使用json字符串来填充我的钛应用程序。但通常我在json字符串前面没有信息,如下例所示:

{
    "id": 1,
    "jsonrpc": "2.0",
    "total": 5,
    "result": [
        {
            "id": 1,
            "guid": "1d4aa3b2-c059-4fa7-a751-9bca735e4ebb",
            "picture": "http://skounis.s3.amazonaws.com/mobile-apps/barebone/photo-1.jpg",
            "title": "Wisi consequat sit zzril.",
            "body": "Ut vulputate te dolor ipsum nonummy, dolore enim accumsan veniam duis, nibh veniam at nulla. Adipiscing, dolore dolor lobortis et qui, consequat ea tation iusto qui, tation velit minim. Delenit elit, feugait nibh illum diam vulputate, feugiat erat et velit veniam, tation ea. Consequat magna et, iriure delenit zzril vel ea, eum amet ut autem consequat, tincidunt. Aliquam adipiscing vero dolore, magna ut vel et veniam, iriure odio ullamcorper erat vulputate, facilisi dolore hendrerit in accumsan, accumsan illum iriure quis nibh, nisl vulputate nostrud enim. Commodo, lorem luptatum erat ut elit, blandit dolor eu adipiscing ipsum, dolor.",
            "tags": ["feugait", "vel", "nulla"]
        }
    ]
}

所以我的问题是我如何编写一个数组,提供与此相同的输出,但我可以编辑首先出现的信息,如total,id和jsonrpc。

谢谢。

1 个答案:

答案 0 :(得分:0)

你可以使用php函数json_decode将你的JSON转换为PHP数组。

以下是手册页:http://php.net/json_decode

使用示例:

<?php
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';

    var_dump(json_decode($json, true));

?>

输出:

array(5) {
    ["a"] => int(1)
    ["b"] => int(2)
    ["c"] => int(3)
    ["d"] => int(4)
    ["e"] => int(5)
}

要生成JSON字符串,请使用json_encode。

您的案例示例:

$array = Array("id"=>1, 
"jsonrpc"=>"2.0", 
"total"=>5, 
"result"=>Array(0=>Array
(
        "id"=>1,
        "guid"=> "1d4aa3b2-c059-4fa7-a751-9bca735e4ebb",
        "picture"=> "http://skounis.s3.amazonaws.com/mobile-apps/barebone/photo-1.jpg",
        "title"=> "Wisi consequat sit zzril.",
        "body"=> "Ut vulputate te dolor ipsum nonummy, dolore enim accumsan veniam duis, nibh veniam at nulla. Adipiscing, dolore dolor lobortis et qui, consequat ea tation iusto qui, tation velit minim. Delenit elit, feugait nibh illum diam vulputate, feugiat erat et velit veniam, tation ea. Consequat magna et, iriure delenit zzril vel ea, eum amet ut autem consequat, tincidunt. Aliquam adipiscing vero dolore, magna ut vel et veniam, iriure odio ullamcorper erat vulputate, facilisi dolore hendrerit in accumsan, accumsan illum iriure quis nibh, nisl vulputate nostrud enim. Commodo, lorem luptatum erat ut elit, blandit dolor eu adipiscing ipsum, dolor.",
        "tags"=>Array(0=>"feugait", 1=> "vel",2=> "nulla")
))
);

var_dump(json_encode($array));