非对象的JSON属性&为foreach提供的参数无效

时间:2015-05-04 18:41:56

标签: php arrays json wordpress

我有一个wordpress函数,它通过Zebra_cURL调用API,然后使用for in来适当地呈现数据。然而,存在不稳定的行为,并且发生以下两个错误:json_decode和第50行。

有问题的行如下:

Trying to get property of non-object in [template file] on line 42

然后我收到错误//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'}; } ,即:

Invalid argument supplied for foreach() in [template file] on line 64

我在这里做错了什么导致这些错误?

这是the full template file的链接。为巨大的代码转储道歉,但我对此有点过分了。

1 个答案:

答案 0 :(得分:0)

You must always verify the output of functions/methods if the result if "as expected"
In your case, you did not check what json_decode() has returned

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]
}