You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP解析JSON报错:Trying to get property of non-object问题求助

问题分析与修复方案

你遇到的Trying to get property of non-object错误,核心问题是错误地将display_informations当成数组遍历,但从你提供的JSON结构来看,它其实是单个对象,不是数组集合。

为什么会报错?

在你的代码里,第二个foreach ($a->display_informations as $b)会遍历display_informations对象的所有属性值(比如字符串、空数组等),这时候$b已经不是对象了,自然无法访问$b->direction,从而触发错误。

修正后的代码

我们只需要去掉多余的嵌套foreach,直接访问display_informations对象里的direction字段,同时加上必要的安全检查,避免意外报错:

$json_source = file_get_contents('https://pastebin.com/raw/TTuV7K7J');

// 检查是否成功获取JSON内容
if (!$json_source) {
    die("无法获取目标JSON数据");
}

$data = json_decode($json_source);

// 验证JSON解析结果和数据结构
if (json_last_error() !== JSON_ERROR_NONE || !isset($data->departures) || !is_array($data->departures)) {
    die("JSON解析失败或数据结构不符合预期");
}

foreach ($data->departures as $departure) {
    // 确保display_informations是存在的对象
    if (isset($departure->display_informations) && is_object($departure->display_informations)) {
        echo $departure->display_informations->direction . '<br />';
    } else {
        // 可选:处理缺失方向信息的情况
        echo "无有效方向信息<br />";
    }
}

额外说明

加上isset()和is_object()检查是为了兼容JSON中可能存在的异常情况(比如某个departures元素没有display_informations字段,或者它不是对象类型),让代码更健壮。

内容的提问来源于stack exchange,提问作者Will

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 03:45:43