I recently ran into an issue where JSON encoding some objects in my code wasn’t working properly. After experimenting, I realized that casting everything to an array before JSON encoding magically fixed things.
Casting an object to an array is simple enough:
$variable_to_array = (array) $object_var;
But, what happens when an object or array contains references to other objects or arrays? The answer is that we then need to recursively cast a given input to an array. But, we don’t necessarily want to recursively cast everything to an array. For example, this is what happens when we cast 1
to an array:
return (array) 1;
=> array(1) {
[0]=>
int(1)
}
A simple fix is to recursively cast non-scalar values to an array. Here’s an example of how we would do that:
/**
* Given mixed input, will recursively cast to an array if the input is an array or object.
*
* @param mixed $input Any input to possibly cast to array.
* @return mixed
*/
function recursive_cast_to_array( $input ) {
if ( is_scalar( $input ) ) {
return $input;
}
return array_map( 'recursive_cast_to_array', (array) $input );
}
Leave a Reply