5

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;
}

3 Answers 3

10

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;
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Best answers are often simplest +1
3

If it's a one-dimensional array, a cast should work:

$obj = (object)$array;

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.