PHP从JSON数组获取信息

时间:2016-03-19 08:33:30

标签: php arrays json

我在服务器上的一个单独文件中有这个JSON数组:

data = '[{"name" : "AAA", "year" : "1999", "plot" : "BBB", "run" : "194 min", "rated" : "PG-13", "score" : "7.7/10", "source" : "DDD", "id" : "000000"}]';

你如何使用PHP获得数组中的“名称”(AAA)?

很抱歉,如果我遗漏任何东西,只需从PHP和JSON开始。

3 个答案:

答案 0 :(得分:0)

在PHP中,您可以从json响应中获取name

// your json response
$string = '[{"name" : "AAA", "year" : "1999", "plot" : "BBB", "run" : "194 min", "rated" : "PG-13", "score" : "7.7/10", "source" : "DDD", "id" : "000000"}]';

$encoded = json_decode($string,TRUE);
print_r($encoded); // complete array
echo $encoded[0]['name']; // print AAA

答案 1 :(得分:0)

$data = '[{"name" : "AAA", "year" : "1999", "plot" : "BBB", "run" : "194 min", "rated" : "PG-13", "score" : "7.7/10", "source" : "DDD", "id" : "000000"}]';

$data_array = json_decode($data);
var_dump(current($data_array)->name);

这是你想要的吗?

答案 2 :(得分:0)

如果您有一些JSON格式的数据,并且想要引用它们中的任何一个。您可以根据您的编程语言使用以下方法: -

PHP: -

$data =  '[{"name" : "AAA", "year" : "1999", "plot" : "BBB", "run" : "194 min", "rated" : "PG-13", "score" : "7.7/10", "source" : "DDD", "id" : "000000"}]';
$parsedData = json_decode($data,TRUE);

现在 $ parsedData 是一个数组,您可以使用密钥来访问值,如

foreach($parsedData as $key => $value)
{
     $name = $value['name'];
}

JavaScript: -

data =  '[{"name" : "AAA", "year" : "1999", "plot" : "BBB", "run" : "194 min", "rated" : "PG-13", "score" : "7.7/10", "source" : "DDD", "id" : "000000"}]';
var parsedData = JSON.parse(data);
var dataCount = parseData.length,index;
for(index = 0 ; index < dataCount ; i++)
{
     var name = parsedData[index]['name']; 
     // var name = parsedData[index].name;  // or 
}