我正在使用file_get_contents($url);
从网址检索JSON
我正在检索的JSON采用以下形式:
[
{
"name" : "Dave",
"age" : 20,
"sex" : "M"
},
{
"name" : "John",
"age" : 31,
"sex" : "M"
},
{
"name" : "Jane",
"age" : 24,
"sex" : "F"
}
]
如何访问这些信息?我一直试图使用json_decode($json, true)
,但它确实没有给出预期的结果。
我希望最终得到一个对象数组,以便我能够做到:
$some_array[1]->name
// John
$some_array[2]->age
// 24
答案 0 :(得分:0)
使用json_decode($json, true)
将为您提供关联数组作为结果。这意味着您将能够使用$decoded[0]['name']
访问数据。如果省略json_decode
上的第二个参数,您将获得所需内容:
$json = '[
{
"name" : "Dave",
"age" : 20,
"sex" : "M"
},
{
"name" : "John",
"age" : 31,
"sex" : "M"
},
{
"name" : "Jane",
"age" : 24,
"sex" : "F"
}
]';
$data = json_decode($json); // default for 2nd parameter is false
var_dump($data);
产生以下输出:
array(3) {
[0]=>
object(stdClass)#1 (3) {
["name"]=>
string(4) "Dave"
["age"]=>
int(20)
["sex"]=>
string(1) "M"
}
[1]=>
object(stdClass)#2 (3) {
["name"]=>
string(4) "John"
["age"]=>
int(31)
["sex"]=>
string(1) "M"
}
[2]=>
object(stdClass)#3 (3) {
["name"]=>
string(4) "Jane"
["age"]=>
int(24)
["sex"]=>
string(1) "F"
}
}
请注意结果中的对象不是任何特殊类型。因此,您的IDE很可能不知道可用的属性。因此,你也不会对它们进行任何类型暗示。