PHP递归地将对象转换为数组

标签 php arrays recursion casting

我正在尝试以递归方式将 php 对象转换为数组。我写的函数是这样的:

public function object_to_array($obj) {
    $array = (array) $obj;
    foreach ($array as $attribute) {
      if (is_array($attribute)) $attribute = $this->object_to_array($attribute);
      if (!is_string($attribute)) $attribute = (array) $attribute;
    }
    return $array;
}

但是,我的外部数组中仍然有对象。为什么是这样?我的功能不正确吗?

最佳答案

这是我的版本。首先它会测试传递的参数是数组还是对象。如果是这样,它将转换为数组(如有必要)然后遍历每个元素(通过引用)并在其上递归运行该函数。当它到达一个标量值时,它只会返回未修改的值。似乎有效:-)

function object_to_array($obj) {
    //only process if it's an object or array being passed to the function
    if(is_object($obj) || is_array($obj)) {
        $ret = (array) $obj;
        foreach($ret as &$item) {
            //recursively process EACH element regardless of type
            $item = object_to_array($item);
        }
        return $ret;
    }
    //otherwise (i.e. for scalar values) return without modification
    else {
        return $obj;
    }
}

关于PHP递归地将对象转换为数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22676150/

相关文章:

php - 如果状态更改为自定义状态,则将自定义元字段值添加到 WooCommerce 订单

php - 通过php向DB插入数据失败

java - 具有头部和尾部的可变数量的嵌套循环

c - 使用 main() 函数递归

Haskell:字符 'i' 处的字符串/字 rune 字中的词法错误

php - 带有 png 扩展名的通用动态图像

php - 在 php 中验证 HTTP post 发件人

python - 优化给定移位的数组距离的成对计算

arrays - 从值字典中获取数组

c - 在 C 中计算多边形面积的问题