PHP:foreach循环重命名对象属性时unset致对象为空的解决方法
解决PHP stdClass对象遍历修改属性名时清空对象的问题
你遇到的问题是因为直接遍历stdClass对象时,迭代过程会受对象属性动态变化的影响——当你在循环里删除原属性并添加新属性,foreach的迭代指针会被干扰,最终导致所有属性被意外删除。
下面提供两种可靠的解决方法:
方法一:转数组处理后转回对象
先把stdClass转成数组,基于数组副本遍历修改,最后转回对象,完全避免迭代干扰:
// 将对象转为数组副本 $customerArr = (array)$customer; $newCustomer = new stdClass(); foreach ($customerArr as $key => $value) { $newKey = str_replace('-', '_', $key); $newCustomer->$newKey = $value; } // 若需要覆盖原对象,执行此句 $customer = $newCustomer;
方法二:遍历初始属性的快照
用get_object_vars()获取对象初始属性的列表(快照),遍历这个静态列表来修改原对象,这样迭代过程不受对象动态修改的影响:
// 获取对象初始属性的静态列表 $props = get_object_vars($customer); foreach ($props as $key => $value) { $newKey = str_replace('-', '_', $key); $customer->$newKey = $value; unset($customer->$key); }
这两种方法都能确保你成功将属性名的横杠替换为下划线,且不会出现对象被清空的问题。
内容的提问来源于stack exchange,提问作者Christopher Ansbaugh
相关产品推荐
相关产品推荐

