Is there a way to convert a multidimensional array
to a stdClass
object in PHP?
Casting as (object)
doesn\'t seem to work recu
You can use the array_map
recursively:
public static function _arrayToObject($array) {
return is_array($array) ? (object) array_map([__CLASS__, __METHOD__], $array) : $array;
}
Works perfect for me since it doesn't cast for example Carbon objects to a basic stdClass (which the json encode/decode does)
EDIT: This function is conversion from object to array.
From https://forrst.com/posts/PHP_Recursive_Object_to_Array_good_for_handling-0ka
protected function object_to_array($obj)
{
$arrObj = is_object($obj) ? get_object_vars($obj) : $obj;
foreach ($arrObj as $key => $val) {
$val = (is_array($val) || is_object($val)) ? $this->object_to_array($val) : $val;
$arr[$key] = $val;
}
return $arr;
}