我如何解码JSON编码的值数组并使用它?

时间:2011-03-09 02:39:31

标签: php json

我目前已将数据库中的以下JSON输出创建为在我的网站上运行的迷你API。我正在尝试使用此API,但我不确定如何。这是示例查询的结果JSON:

{ "uploads":[ { "upload":{ "id":"74", "uploaded":"2011-03-08 11:43:36", "filename":"padthai.jpg", "owner":"2", "what":"Pad+Thai", "where":"Hot+Basil+Cafe", "details":"Thai+food!", "rating":"3", "lat":"37.938351", "lng":"-122.024483" } }, { "upload":{ "id":"73", "uploaded":"2011-03-08 11:39:36", "filename":"chirashi.jpg", "owner":"2", "what":"Chirashi+Bowl", "where":"Goshi", "details":"Freshest+fish+in+town!", "rating":"5", "lat":"35.267742", "lng":"-120.670570" } }, { "upload":{ "id":"72", "uploaded":"2011-03-08 11:38:04", "filename":"innout.jpg", "owner":"2", "what":"Double+Double,+Hamburger,+and+Fries", "where":"In-N-Out", "details":"I+love+their+fries!", "rating":"5", "lat":"35.126698", "lng":"-120.597206" } }, { "upload":{ "id":"71", "uploaded":"2011-03-08 11:20:45", "filename":"artspecialroll.jpg", "owner":"2", "what":"Art+Special+Roll", "where":"Happy+Roll", "details":"nom+nom+nom", "rating":"5", "lat":"37.976585", "lng":"-122.033646" } }, { "upload":{ "id":"69", "uploaded":"2011-03-08 11:18:29", "filename":"l.jpg", "owner":"2", "what":"Bun+Bo+Hue", "where":"Saigon+Bistro", "details":"Perfect~", "rating":"5", "lat":"37.973385", "lng":"-122.041183" } }, { "upload":{ "id":"68", "uploaded":"2011-03-08 11:15:33", "filename":"IMG_2811.JPG", "owner":"2", "what":"Asiago+Roast+Beef", "where":"Panera+Bread", "details":"Yummy", "rating":"5", "lat":"35.262539", "lng":"-120.678101" } }, { "upload":{ "id":"67", "uploaded":"2011-03-08 10:56:33", "filename":"IMG_2764.JPG", "owner":"2", "what":"Ninja+Roll+and+Salmon+Hand+Roll", "where":"Shin's", "details":"Ninja+roll+is+hella+good!", "rating":"4", "lat":"35.281921", "lng":"-120.660889" } } ] }

我如何专门解码这些信息,并能够在循环中使用它来显示访问我想要的每个上传元素的所有“上传”?

特定代码示例将是有用/需要的!有用的JSON资源将不胜感激!

3 个答案:

答案 0 :(得分:4)

如果您将JSON作为字符串接收,则可以将其转换为json_decode($that_string, true);

的数组

您可以访问以下数据:

$array = json_decode($json, true);
foreach($array['uploads'] as $foo=>$upload)
{
    foreach($upload as $key=>$value)
    {
    echo $value['what'] . " has a rating of " . $value['rating'] . "\n";
    }
}

答案 1 :(得分:2)

答案 2 :(得分:2)

http://php.net/manual/en/function.json-decode.php

<?php

$json = '{"foo-bar": 12345}';

$obj = json_decode($json);

print $obj->{'foo-bar'}; // 12345

?>