Reputation: 238717
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;
}
Upvotes: 5
Views: 615
Reputation: 2904
This works for me
if (is_array($array)) {
$obj = new StdClass();
foreach ($array as $key => $val){
$key = str_replace("-","_",$key)
$obj->$key = $val;
}
$array = $obj;
}
make sure that str_replace is there as '-' is not allowed within variable names in php, as well as:
Naming Rules for Variables
* A variable name must start with a letter or an underscore "_"
* A variable name can only contain alpha-numeric characters and underscores (a-z, A-Z, 0-9, and _ )
* A variable name should not contain spaces. If a variable name is more than one word, it should be separated with an underscore ($my_string), or with capitalization ($myString)
So, since these are permitted in arrays, if any of them comes in the $key from the array you are converting, you will have nasty errors.
Upvotes: 0
Reputation: 268344
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;
}
}
Upvotes: 10
Reputation: 449425
If it's a one-dimensional array, a cast should work:
$obj = (object)$array;
Upvotes: 3