我正在尝试获取值来自嵌套的JSON,其中包含带空格的键。我有这个错误:
-
注意:正在尝试获取中非对象的属性"Submit Date"json.php在第47行
-
注意:正在尝试获取json.php中非对象的属性"Entry ID"在线46
{ "entries": [ { "values": { "Entry ID": "INC000000001", "Submitter": "Remedy Application Service", "Assigned Group": "TI WIN", "Priority": "Medium", "Submit Date": "2022-07-20T22:27:01.000+0000", "Assignee": "Example asignee" }, "_links": { } } ] }
我的PHP代码
<?php
$response = curl_exec($curl);
$data = json_decode($response);
foreach($data->entries as $entr)
{
foreach($entr->values as $valores)
{
$entry_id=$valores->{'Entry ID'};
$submit_date=$valores->{'Submit Date'};
}
}
?>
打印输出:
Array
(
[entries] => Array
(
[0] => Array
(
[values] => Array
(
[Entry ID] => INC000000001
[Submitter] => Remedy Application Service
[Assigned Group] => TI WIN
[Priority] => Medium
[Submit Date] => 2022-07-20T22:27:01.000+0000
[Assignee] => Example asignee
)
)
)
)
错误在哪里?
有什么方法可以得到这些值?
您的代码与print_r
输出不一致;在您的代码中,$data
将是一个对象(因为您没有为json_decode
指定$associative
参数(,看起来如下:
stdClass Object
(
[entries] => Array
(
[0] => stdClass Object
(
[values] => stdClass Object
(
[Entry ID] => INC000000001
[Submitter] => Remedy Application Service
[Assigned Group] => TI WIN
[Priority] => Medium
[Submit Date] => 2022-07-20T22:27:01.000+0000
[Assignee] => Example asignee
)
[_links] => stdClass Object
(
)
)
)
)
entries
数组中每个条目的values
属性是一个对象,而不是一个数组,所以你不能迭代它。相反,只需直接访问属性:
foreach($data->entries as $entr) {
$entry_id=$entr->values->{'Entry ID'};
$submit_date=$entr->values->{'Submit Date'};
var_dump($entry_id, $submit_date);
}
输出(用于您的样本数据(:
string(12) "INC000000001"
string(28) "2022-07-20T22:27:01.000+0000"
3v4l.org 上的演示