如果JSON字符串的名称"Some Items"
中有空格(有更准确的术语吗?),在使用json_decode($json_string)
后,如何在PHP中访问它?从API返回的数据甚至需要这个名称吗?
JSON字符串
{"Some Items":[{"post_id":"1284"},{"post_id":"1392"},{"post_id":"1349"}]}
这些不起作用
$data = json_decode($json_string);
$data = $data->"Some Items"; // invalid PHP
$data = $data["Some Items"]; // Cannot use object of type stdClass as array
您需要使用大括号($object->{'...'}
)语法:
$data->{'Some Items'}
如果你不喜欢大括号的想法,你可以使用动态访问器业务:
$someitems = "Some Items";
var_dump($data->$someitems);
或者,您可以将$data强制转换为数组并使用方括号:
$data = (array)json_decode($json_str);
var_dump($data['Some Items']);
json_decode
有一个开关,所以您不需要使用强制转换。
$data = json_decode($json_str, true);
var_dump($data);
试试这个
$data->{'Some Items'};
尝试
<?php
$json = '{"Some Items":[{"post_id":"1284"},{"post_id":"1392"},{"post_id":"1349"}]}';
$decoded = json_decode($json);
// for example
echo($decoded->{"Some Items"}[0]->post_id);
?>