递归提取嵌套对象Leg信息时遇stdClass::$Legs未定义错误
解决Undefined property: stdClass::$Legs错误的方案
错误原因
你的代码直接访问$ride->Legs,但根据提供的原始数据结构,顶层对象不存在名为Legs的属性——顶层对象本身就是一个Leg条目,嵌套的子Leg数据是存放在Frequencies属性下,而非Legs中。同时递归函数的遍历逻辑和原始结构不匹配,导致触发属性未定义的错误。
修正方案
核心改动点
- 顶层循环直接将当前
$ride作为第一个Leg条目加入结果集 - 递归遍历的目标从
Legs改为Frequencies,匹配原始数据的嵌套结构 - 增加属性存在性检查,避免空值或不存在的属性引发报错
修正后的完整代码
foreach ($rides as $rideskey => $ride) { $result = ["Legs" => []]; $index = 0; // 处理顶层Leg条目 $this->processLeg($ride, $result, $index); // 将收集到的所有Leg赋值回父对象的Legs属性 $rides[$rideskey]->Legs = $result["Legs"]; } /** * 递归处理Leg条目及其嵌套的Frequencies子项 * @param stdClass $item 当前处理的Leg/Frequencies条目 * @param array &$result 存储最终Leg集合的结果数组 * @param int &$index 用于生成Leg的唯一索引 */ function processLeg($item, &$result, &$index) { // 复制当前条目并移除Frequencies(后续单独递归处理) $leg = clone $item; unset($leg->Frequencies); // 将当前Leg加入结果集,分配唯一索引 $result["Legs"][$index++] = $leg; // 检查当前条目是否存在非空的Frequencies,递归处理子项 if (isset($item->Frequencies) && !empty($item->Frequencies)) { foreach ($item->Frequencies as $subItem) { $this->processLeg($subItem, $result, $index); } } }
代码说明
- 顶层处理:直接把每个
$ride(原始顶层对象)作为第一个Leg加入结果,符合目标结构要求 - 递归逻辑:遍历每个条目下的
Frequencies子项,将每个子项也作为Leg收集,同时继续递归处理子项的Frequencies,直到所有嵌套层级处理完毕 - 容错处理:用
isset()和!empty()检查Frequencies属性,避免处理空的子项(比如原始结构中的Third空节点)时触发错误 - 对象复制:使用
clone复制对象,避免修改原始数据结构;如果不需要保留原始数据,可以直接操作原对象,省略clone步骤
内容的提问来源于stack exchange,提问作者ternary
相关产品推荐
相关产品推荐

