Is there a PHP function that will do this automatically?
if (is_array($array)) {
$obj = new StdClass();
foreach ($array as $key => $val){
$obj->$key = $val;
}
$array = $obj;
}
Converting an array to a StdClass object is super-simple with PHP. Using a type casting method you can quickly carry out an array to StdClass conversion in one line of code.
The stdClass is the empty class in PHP which is used to cast other types to an object. The stdClass is not the base class of the objects. If an object is converted to an object, it is not modified. But, if an object type is converted/type-casted an instance of stdClass is created if it is not NULL.
To convert an array into the object, stdClass () is used. The stdClass () is an empty class, which is used to cast other types to object. If an object is converted to object, its not modified. But, if object type is converted/type-casted an instance of stdClass is created, if it is not NULL. If it is NULL, the new instance will be empty.
The stdClass () is an empty class, which is used to cast other types to object. If an object is converted to object, its not modified. But, if object type is converted/type-casted an instance of stdClass is created, if it is not NULL. If it is NULL, the new instance will be empty. Example 1: It converts an array into object using stdClass.
Why not just cast it?
$myObj = (object) array("name" => "Jonathan");
print $myObj->name; // Jonathan
If it's multidimensional, Richard Castera provides the following solution on his blog:
function arrayToObject($array) {
if(!is_array($array)) {
return $array;
}
$object = new stdClass();
if (is_array($array) && count($array) > 0) {
foreach ($array as $name=>$value) {
$name = strtolower(trim($name));
if (!empty($name)) {
$object->$name = arrayToObject($value);
}
}
return $object;
} else {
return FALSE;
}
}
If it's a one-dimensional array, a cast should work:
$obj = (object)$array;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With