문제

Following this question, I use this function to convert arrays to objects,

function array_to_object($array)
{
    if(!is_array($array)) {
        return $array;
    }

    $object = new stdClass();
    foreach($array as $key => $value)
    {
        $key = (string) $key ;
        $object->$key = is_array($value) ? array_to_object($value) : $value;
    }
    return $object;
}

So,

$obj =  array('qualitypoint', 'technologies', 'India');

result,

stdClass Object
(
    [0] => qualitypoint
    [1] => technologies
    [2] => India
)

But now I need to convert the object back to an array so that I can get this result,

Array
(
    [0] => qualitypoint
    [1] => technologies
    [2] => India
)

is it possible?

도움이 되었습니까?

해결책

Another way to achieve this is:

$array = array(json_decode(json_encode($object), true));

When I tested, I had no problems with inaccessible properties.

Update: It also works with

$object = new stdClass();
$object->{0} = 'qualitypoint';
$object->{1} = 'technologies';
$object->{2} = 'India';

다른 팁

What would be nice, but will not really work as it is

Normally a good starting approach is to simply cast the object to array:

$arr = (array) $obj;

If an object is converted to an array, the result is an array whose elements are the object's properties. The keys are the member variable names, with a few notable exceptions: integer properties are unaccessible; private variables have the class name prepended to the variable name; protected variables have a '*' prepended to the variable name. These prepended values have null bytes on either side.

Unfortunately this will not work for you because the properties have "integer" names.


A variation on the above is get_object_vars:

$arr = get_object_vars($obj);

One important point here is that get_object_vars respects visibility, which means that it will only give you the public properties of $obj since you are not calling it from within a method of $obj.

However this will also not work in this case: get_object_vars will also not give you integer-named properties.

What will work (but is not nice)

Iterating over an object will also give you the visible properties it has (only public properties in this case), but it will also process properties with integer names:

$arr = array();
foreach($obj as $k => $v) {
    $arr[$k] = $v;
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top