【问题标题】:Converting Multidimensional Mixed Object and Array to Array while Preserving Object Names as Keys - PHP [duplicate]将多维混合对象和数组转换为数组,同时将对象名称保留为键 - PHP [重复]
【发布时间】:2012-12-03 16:19:46
【问题描述】:

可能重复:
convert object to array

假设我有一个这样的数组:(请注意,某些方法/对象可能受到保护,因此必须在自己的类中访问它们)

array(
    0=> objectname{
        [method1:protected]=> array(
            ["key1"] => object2{
                [method2]=> array(
                    0 => "blah"
                )
            }
        )
    }
    1=> objectname{
        [method1:protected]=> array(
            ["key1"] => object2{
                [method2]=> array(
                    0 => "blah"
                )
            }
        )
    }
)

我想将所有这些转换成一个数组。我通常会使用这个:

protected function _object_to_array($obj){

    if(is_object($obj)) $obj = (array) $obj;

    if(is_array($obj)) {

        $new = array();
        foreach($obj as $key => $val) {
            $new[$key] = self::_object_to_array($val);
        }

    }else{

        $new = $obj;

    }

    return $new;

}

问题在于这不会保留对象名称。我希望对象名称成为一个额外的键,将数组提升一个维度。例如,将 0 替换为 objectname 可能有效,但最好创建如下内容:

array(
    0=> array(
        objectname=> array(
            ...blah blah
        )
    )
)

【问题讨论】:

  • 不是重复的。我使用该代码构建了我的第一个流程。
  • 不,它是重复的。正确执行此操作的关键在于该问题的第一个公认答案:在您希望转换为数组的对象中调用get_object_vars()。这将正确处理受保护的和私有的成员变量。此外,方法和成员变量之间存在差异:您似乎混淆了这些术语。首先,如果您将它们的对象转换为数组,则方法不会出现在结果数组中,而成员变量会。我创建的这个要点应该展示一些东西:gist.github.com/4196621
  • 我遇到的具体问题不是获取对象变量。它正在获取对象的名称。我用这个 $obj_name = get_class($obj); 解决了这个问题

标签: php arrays object


【解决方案1】:

想通了。

然而新的问题是,受保护的方法最终会变成像 [*formermethodturnedkey] 这样的键。它们似乎无法访问。怎么能像这样访问密钥?

protected function _object_to_array($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)
    $obj_name = false;
    if(is_object($obj)){
        $obj_name = get_class($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 = array();

        //initiate the recursion
        foreach($obj as $key => $val) {
            //we don't want those * infront of our keys due to protected methods
            $new[$key] = self::_object_to_array($val);
        }

        //now if the obj_name exists, then the new array was previously an object
        //the new array that is produced at each stage should be prefixed with the object name
        //so we construct an array to contain the new array with the key being the object name
        if(!empty($obj_name)){
            $new = array(
                $obj_name => $new,
            );
        }

    }else{

        $new = $obj;

    }

    return $new;

}

【讨论】:

    猜你喜欢
    • 2017-02-16
    • 1970-01-01
    • 1970-01-01
    • 2014-03-08
    • 2019-08-06
    • 2019-07-14
    • 2017-06-20
    • 2021-12-28
    相关资源
    最近更新 更多