Reputation: 57286
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?
Upvotes: 1
Views: 147
Reputation: 437854
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.
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;
}
Upvotes: 3
Reputation: 3262
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';
Upvotes: 2