【问题标题】:Converting nested objects in PHP to an array [duplicate]将PHP中的嵌套对象转换为数组[重复]
【发布时间】:2019-03-27 08:39:02
【问题描述】:

我最近遇到了一个问题,我必须将用作模型的对象(强制数据类型等)转换为数组以进行进一步处理。至少公共和私人财产必须出现。

查看堆栈溢出,我发现了各种方法,但大多数仅适用于单维(无嵌套模型),而多维版本总是将完整的模型名称留在数组键中。

如何在保持代码干净的同时完成这项工作?

编辑:由于有人将此标记为重复,因此不是。链接为重复的 2 个问题(我什至提到了自己)并不相同,因为它们要么不适用于多维对象,要么保留包含类名前缀的数组键。我在搜索中测试了这两种解决方案,但都没有完全按照我的描述进行。

【问题讨论】:

    标签: php arrays object type-conversion


    【解决方案1】:

    受给定答案over here 的启发,我对其进行了一些更改,因此我们不再获得名称前缀,然后将其更改为可以在对象内部使用的特征。然后可以使用$object->toArray(); 调用该实例。当前对象被假定为默认对象,但也可以传递另一个实例。

    从对象内部使用时,所有私有属性也将返回到数组中。

    trait Arrayable
    {
        public function toArray($obj = null)
        {
            if (is_null($obj)) {
                $obj = $this;
            }
            $orig_obj = $obj;
    
            // We want to preserve the object name to the array
            // So we get the object name in case it is an object before we convert to an array (which we lose the object name)
            if (is_object($obj)) {
                $obj = (array)$obj;
            }
    
            // If obj is now an array, we do a recursion
            // If obj is not, just return the value
            if (is_array($obj)) {
                $new = [];
                //initiate the recursion
                foreach ($obj as $key => $val) {
                    // Remove full class name from the key
                    $key = str_replace(get_class($orig_obj), '', $key);
                    // We don't want those * infront of our keys due to protected methods
                    $new[$key] = self::toArray($val);
                }
            } else {
                $new = $obj;
            }
    
            return $new;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2013-12-14
      • 2021-06-16
      • 1970-01-01
      • 2018-10-09
      • 1970-01-01
      • 1970-01-01
      • 2015-03-26
      • 2019-01-31
      相关资源
      最近更新 更多