Convert StdClass Object To Array In PHP
Answer :
The easiest way is to JSON-encode your object and then decode it back to an array:
$array = json_decode(json_encode($object), true);
Or if you prefer, you can traverse the object manually, too:
foreach ($object as $value)
$array[] = $value->post_id;
Very simple, first turn your object into a json object, this will return a string of your object into a JSON representative.
Take that result and decode with an extra parameter of true, where it will convert to associative array
$array = json_decode(json_encode($oObject),true);
Try this:
$new_array = objectToArray($yourObject);
function objectToArray($d)
{
if (is_object($d)) {
// Gets the properties of the given object
// with get_object_vars function
$d = get_object_vars($d);
}
if (is_array($d)) {
/*
* Return array converted to object
* Using __FUNCTION__ (Magic constant)
* for recursive call
*/
return array_map(__FUNCTION__, $d);
} else {
// Return array
return $d;
}
}
Comments
Post a Comment