1

重複の可能性:
オブジェクトを配列に変換

私がこのような配列を持っているとしましょう:(メソッド/オブジェクトのいくつかは保護されている可能性があるので、それらは独自のクラスでアクセスする必要があることに注意してください)

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;

}

問題は、これがオブジェクト名を保持しないことです。オブジェクト名を、配列を1次元上に上げる追加のキーにしたいと思います。たとえば、objectnameの0を置き換えることは機能する可能性がありますが、次のようなものを作成する方がよいでしょう。

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

1 に答える 1

2

理解した。

ただし、新しい問題として、保護されたメソッドは[*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;

}
于 2012-12-03T17:13:04.717 に答える