Php 非对象的JSON属性&;为foreach提供的参数无效
我有一个wordpress函数,它通过Zebra_cURL调用API,然后使用Php 非对象的JSON属性&;为foreach提供的参数无效,php,arrays,json,wordpress,Php,Arrays,Json,Wordpress,我有一个wordpress函数,它通过Zebra_cURL调用API,然后使用json_decode适当地呈现数据。然而,存在不稳定的行为,并且出现了以下两个错误:试图通过第42行和第50行获取[template file]中非对象的属性 有关的行数如下: //Course display callback function function display_courses($result) { $result->body = json_decode(html_entit
json_decode
适当地呈现数据。然而,存在不稳定的行为,并且出现了以下两个错误:试图通过第42行和第50行获取[template file]中非对象的属性
有关的行数如下:
//Course display callback function
function display_courses($result) {
$result->body = json_decode(html_entity_decode($result->body));
$title = $result->body[0]->{'Title'};
$term = $result->body[0]->{'Term'};
$meetings = $result->body[0]->{'Meetings'};
$status = $result->body[0]->{'Status'};
$course_number = $result->body[0]->{'OfferingName'};
$clean_course_number = preg_replace('/[^A-Za-z0-9\-]/', '', $course_number);
$credits = $result->body[0]->{'Credits'};
$instructor = $result->body[0]->{'InstructorsFullName'};
$description = $result->body[0]->{'SectionDetails'}[0]->{'Description'};
}
然后,我在第64行的[template file]中得到一个错误为foreach()提供的无效参数,即:
//Call callback function
function parse_courses($result) {
$result->body = json_decode(html_entity_decode($result->body));
$course_data = array();
foreach($result->body as $course) {
[code]
}
[more code]
}
我到底做错了什么导致了这些错误
这里有到的链接。对于大量的代码转储,我深表歉意,但我对此有点不知所措。如果结果是“如预期的那样”
,则必须始终验证函数/方法的输出
在您的情况下,您没有检查json\u decode()
返回的内容
function parse_courses($result) {
$result = json_decode(html_entity_decode($result->body));
if ((!is_array ($result) && !is_object($result)) ||
(is_array($result) || count($result) == 0) ||
(json_last_error() != JSON_ERROR_NONE)) { // only for PHP >= 5.3.0
// log the error or warning here ...
// $input = $result;
// $output = print_r ($result, TRUE);
// Only for PHP >= 5.3.0
// json_last_error();
// json_last_error_msg();
return -1;
}
$result->body = $result;
$course_data = array();
foreach($result->body as $course) {
[code]
}
[more code]
}