From the first Google hit for "PHP object to assoc array" we have this:
function object_to_array($data)
{/**
* @param ifarray|object (is_array($data)
||* is_object@return array
*/
function object_to_array($data))
{
$result = [];
foreach ($data as $key => $value)
{
$result[$key] = (is_array($value) || is_object($value)) ? object_to_array($value) : $value;
}
return $result;
}
return $data;
}
The original source iswas atfrom codesnippets.joyent.com and has been changed according to @SpYk3HH's comment; see also Object Iteration.
To compare it to the solution of json_decode & json_encode, this one seems faster. Here is a random benchmark (using the simple time measuring):
$obj = (object) [
'name' =>'Mike',
'surname' =>'Jovanson',
'age' =>'45',
'time' =>1234567890,
'country' =>'Germany',
];
##### 100 000 cycles ######
* json_decode(json_encode($var)) : 4.15 sec
* object_to_array($var) : 0.93 sec