我有以下代码,只想访问以下信息并打印Status
"Email": { "Status": "in-queue" }
我对PHP很陌生,所以我为任何错误道歉,为一堂课学习。
{
"APIResponse": {
"ResponseStatus": 1,
"Email": {
"EmailSid": "12893712893789",
"SentEmails": "my@email.com",
"Date": "2017-02-07 22:53:26",
"Subject": "700message",
"Status": "in-queue",
"TotalEmailSent": 1,
"TotalPrize": "0.0100",
"ApiVersion": "2"
}
}
}
我知道如何在JavaScript中执行此操作,但对PHP来说似乎有点不同。
感谢所有人的帮助! :)
答案 0 :(得分:1)
这是一个快速的PHP示例,介绍如何将JSON字符串转换为数组并显示值:
$json = '{
"APIResponse": {
"ResponseStatus": 1,
"Email": {
"EmailSid": "12893712893789",
"SentEmails": "my@email.com",
"Date": "2017-02-07 22:53:26",
"Subject": "700message",
"Status": "in-queue",
"TotalEmailSent": 1,
"TotalPrize": "0.0100",
"ApiVersion": "2"
}
}
}';
$array = json_decode($json, true);
echo $array['APIResponse']['Email']['Status'];
注意每个子节点如何成为关联数组中的子节点。您还可以执行print_r($array);
以本机PHP关联数组格式查看整个结构。
答案 1 :(得分:0)
<?php
$json = '{
"APIResponse": {
"ResponseStatus": 1,
"Email": {
"EmailSid": "12893712893789",
"SentEmails": "my@email.com",
"Date": "2017-02-07 22:53:26",
"Subject": "700message",
"Status": "in-queue",
"TotalEmailSent": 1,
"TotalPrize": "0.0100",
"ApiVersion": "2"
}
}
}';
// if this API response's JSON is being stored as a string type local variable decode it first.
$decoded_json = json_decode($json, true);
//Optional but helps when programing var_dump($decoded_json); Use this to help visualize the nested array variables you need to access.
// Use each array key to walk into and access the desired value
echo $decoded_json['APIResponse']['Email']['Status'];
?>
*根据评论中的问题编辑以解决错误:
虽然仍然确定如上所述首先解码Json,但下面应该允许您访问这些值。
echo $decoded_json['APIResponse']['Errors']['Error'][0]['Code'];
echo $decoded_json['APIResponse']['Errors']['Error'][0]['Message'];
最后,如果你遇到麻烦,还有更多建议。尝试从最外层开始一次访问一个阵列并继续工作,总是帮助我!