Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: How to turn an array into a StdClass object?

Tags:

php

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;
}
like image 462
Andrew Avatar asked Dec 11 '09 00:12

Andrew


People also ask

How to convert an array to a stdClass in PHP?

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.

What is the use of stdClass in PHP?

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.

How to convert array to object in C++?

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.

What is stdClass() in C++?

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.


2 Answers

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;
    }
}
like image 171
Sampson Avatar answered Sep 24 '22 19:09

Sampson


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

$obj = (object)$array;
like image 44
Pekka Avatar answered Sep 21 '22 19:09

Pekka