-
-
Save victorbstan/744478 to your computer and use it in GitHub Desktop.
<?php | |
/* | |
This function saved my life. | |
found on: http://www.sitepoint.com/forums//showthread.php?t=438748 | |
by: crvandyke | |
It takes an object, and when all else if/else/recursive functions fail to convert the object into an associative array, this one goes for the kill. Who would'a thunk it?! | |
*/ | |
$array = json_decode(json_encode($object), true); |
Be care full if use encodings other than UTF-8. If you use that, json_encode
will return false
.
See here https://www.php.net/manual/de/function.json-encode.php#115733
This will not be be applicable if the properties of the object you are trying to convert are declared as private
You could always create the getter for the object like this (implemented in a form of an universal trait)
trait ThrowingGetter
{
public function __get($propertyName)
{
if (property_exists($this, $propertyName)) {
return $this->$propertyName;
}
throw new \UnexpectedValueException(sprintf('Niceprice: The property \'%s\' does not exist on %s class.', $propertyName, __CLASS__));
}
}
And use it in as many objects as you like (use ThrowingGetter
).
This way you keep your object immutable, read-only.
The initial
$array = json_decode(json_encode($object), true);
will not work straight like this if your nested objects are custom, not stdClass
type objects. For this to work on these too you should implement JsonSerializable
interface on your custom nested objects. See the respective PHP documentation.
just in case performance matters
function objectToArray($object)
{
if(!is_object($object) && !is_array($object)) {
return $object;
}
return array_map('objectToArray', (array) $object);
}
from SO
$array = json_decode(json_encode($object), true);
Absolutely brilliant. You, sir, are a genius.
ArrayObject::getArrayCopy()
return shallow copy of array.