483

How can I convert an array like this to an object?

[128] => Array
    (
        [status] => "Figure A.
 Facebook's horizontal scrollbars showing up on a 1024x768 screen resolution."
    )

[129] => Array
    (
        [status] => "The other day at work, I had some spare time"
    )
matronator
  • 465
  • 6
  • 13
streetparade
  • 32,000
  • 37
  • 101
  • 123

35 Answers35

789

In the simplest case, it's probably sufficient to "cast" the array as an object:

$object = (object) $array;

Another option would be to instantiate a standard class as a variable, and loop through your array while re-assigning the values:

$object = new stdClass();
foreach ($array as $key => $value)
{
    $object->$key = $value;
}

As Edson Medina pointed out, a really clean solution is to use the built-in json_ functions:

$object = json_decode(json_encode($array), FALSE);

This also (recursively) converts all of your sub arrays into objects, which you may or may not want. Unfortunately it has a 2-3x performance hit over the looping approach.

Warning! (thanks to Ultra for the comment):

json_decode on different enviroments converts UTF-8 data in different ways. I end up getting on of values '240.00' locally and '240' on production - massive dissaster. Morover if conversion fails string get's returned as NULL

Community
  • 1
  • 1
jlb
  • 19,090
  • 8
  • 34
  • 65
  • 46
    "as variables cannot start with numbers", yes they can: $object->{3} = 'xyz'; – chelmertz Dec 10 '09 at 08:54
  • 13
    "has a 2-3x performance hit" Which is an unfair comparison, as the latter method returns recursive objects, while the looping approach without further conditions (as in the answer of @streetparade) only converts the first level. – feeela May 13 '13 at 13:07
  • 10
    @feeela I don't think it's unfair at all.. i did mention that it does the conversion recursively. Also, the 2-3x performance hit was arrived at using an flat input array (which wouldn't use any recursion) – jlb May 13 '13 at 14:15
  • 9
    WARNING! json_decode on different enviroments converts UTF-8 data in different ways. I end up getting on of values '240.00' locally and '240' on production - massive dissaster. Morover if conversion fails string get's returned as NULL – Szymon Toda Nov 05 '14 at 15:34
  • Can this be used with a custom class, *not* `stdClass()`? And what about the json method? I doubt this would use any defined class structure – phil294 Dec 25 '16 at 22:37
  • Regarding the json_decode(...,false) solution, i noticed, that, if the array has no keys set, it doesnt work either. E.g. json_decode(json_encode(['test']),false); returns an array, which makes sense, but might be a problem regarding this specific quations from the op. – John Doe Jun 28 '18 at 14:04
  • 2
    Note when using the json_* functions: references (e.g. to other arrays) stored in the original array will be duplicated in this case. Say the key `x` in the array holds a reference to another array. Then `$object->x` after execution of your one-liner will be a duplicate of `$array['x']`, not any more a reference to the original array. This might be harmless in some applications, but for large arrays it wastes memory and might mess up execution if the reference is being used later on. – The Coprolal Dec 13 '18 at 14:49
  • @chelmertz In php7 `$obj->(3)` gives error. Instead use a variable `$obj->$foo` where `$foo=3` or `$foo=(3)` or `$foo="3"`. All works ! – umesh kadam Aug 03 '19 at 07:53
  • @umeshkadam that's because `$obj->(3)` is a syntax error. I literally just now ran an example in php 7.3 to show the point, and it does in fact work. Also, your `$obj->$foo` isn't a great way to write it because it implies a variable variable, which while equivalent, is hard to read and comprehend. don't do it (IMHO) – Zarathuztra Oct 04 '19 at 02:21
179

you can simply use type casting to convert an array to object.

// *convert array to object* Array([id]=> 321313[username]=>shahbaz)
$object = (object) $array_name;

//now it is converted to object and you can access it.
echo $object->username;
Shahbaz
  • 3,433
  • 1
  • 26
  • 43
163

The easy way would be

$object = (object)$array;

But that's not what you want. If you want objects you want to achieve something, but that's missing in this question. Using objects just for the reason of using objects makes no sense.

Jeff Puckett
  • 37,464
  • 17
  • 118
  • 167
johannes
  • 15,807
  • 3
  • 44
  • 57
  • 2
    doesnt work, i did that before i asked the question here so there must be another way to doit – streetparade Dec 08 '09 at 19:00
  • 29
    Why does he have to give his reason for wanting to use objects? I don't think that's relevant to *how* it's done. Maybe he needs to json_encode them, or serialize them? There could be dozens of reasons to do this. – zombat Dec 08 '09 at 19:06
  • hmm.. i looked at the browser output it looks like this object(stdClass)#150 (130) { [0]=> array(1) { ["status"]=> string(130) "At long last Mac and Linux users don't have to feel like second class citizens in Chrome land: they've got official beta versio…" } officialy that is an object but how to iterate throw this that i can acces status like $obj->status any idea? – streetparade Dec 08 '09 at 19:06
  • zombat, JSON encode is no reason for using an object, there is a flag to json_encode() to use objects. with serialize one would need a specific object type expected by the receiver. And in general I try to help with the _actual_ problem. for me this question implies that there is an architectural mistake somewhere else. – johannes Dec 08 '09 at 19:15
  • 1
    Old conversation but I sometimes use objects only because I prefer $o->thing over $a["thing"] – senecaTheMeek Dec 14 '22 at 19:09
126

Quick hack:

// assuming $var is a multidimensional array
$obj = json_decode (json_encode ($var), FALSE);

Not pretty, but works.

Edson Medina
  • 9,862
  • 3
  • 40
  • 51
  • 2
    I actually love this solution, using built in functions instead of user-defined is always quicker, and this one works great. Thanks for the tip. – aknatn May 26 '12 at 20:17
  • @Oddant This solves the problem mentioned above (convert an array into an object). Your rant should be directed into the main post, not my solution. – Edson Medina May 29 '13 at 08:45
  • @EdsonMedina I did, my post is way too down though. – vdegenne May 29 '13 at 09:25
  • 1
    @Oddant, to be fair to @EdsonMedina, the original question does not specify what visibility the attributes need, and since OP does not use `$this` in the comments that follow as the accessor it is heavily implied he/she desires a `stdClass` instance as output and not a user-defined class such as your answer uses. I agree on the elegance of this solution but unfortunately it's a pretty commonly employed pattern to solve this problem with nested arrays where casting to object won't work. It's also possible that OP is using an interface that requires and object as input and not an array. – DeaconDesperado Jun 19 '13 at 19:49
  • 3
    Don't forget that using this way you will lose all but the basic types. DateTime will be converter stdObject for example. – Denis Pshenov Nov 04 '14 at 17:33
  • 1
    Just noticed, that this doesn't work for simple arrays like this: json_decode(json_encode(['test']),false); This gives the same array as it was used for the input – John Doe Jun 28 '18 at 14:12
  • 1
    @JohnDoe the question is referring to associative arrays, not simple arrays. – Edson Medina Jun 29 '18 at 16:15
  • 1
    @EdsonMedina Yeah, i knew that. This question is one of the first results you find on google if you search for converting an array to an object. So i thought this detail might be relevant for someone. Especially the original Array from the op suggests that the answers might work for simple arrays too. – John Doe Jul 01 '18 at 09:24
105

Here are three ways:

  1. Fake a real object:

    class convert
    {
        public $varible;
    
        public function __construct($array)
        {
            $this = $array;
        }
    
        public static function toObject($array)
        {
            $array = new convert($array);
            return $array;
        }
    }
    
  2. Convert the array into an object by casting it to an object:

    $array = array(
        // ...
    );
    $object = (object) $array;
    
  3. Manually convert the array into an object:

    $object = object;
    foreach ($arr as $key => $value) {
        $object->{$key} = $value;
    }
    
Chris Forrence
  • 10,042
  • 11
  • 48
  • 64
Julius F
  • 3,434
  • 4
  • 29
  • 44
50

It's way too simple, This will create an object for recursive arrays as well:

$object = json_decode(json_encode((object) $yourArray), FALSE);
DPP
  • 12,716
  • 3
  • 49
  • 46
29

I also had this issue, but I noticed that json_decode converts JSON array to object.

So, I came about my solution by using json_encode($PHPArray) which returns A JSON string of object, then I decoded the string with Json_decode($string) and it would return a perfectly structured object. Shorthand

$object = json_decode(json_encode($array));

Or

$jsonString = json_encode($array);
$object = json_decode($jsonString);
Dharman
  • 30,962
  • 25
  • 85
  • 135
Uchephilz
  • 508
  • 5
  • 7
25

Depending on where you need that and how to access the object there are different ways to do it.

For example: just typecast it

$object =  (object) $yourArray;

However, the most compatible one is using a utility method (not yet part of PHP) that implements standard PHP casting based on a string that specifies the type (or by ignoring it just de-referencing the value):

/**
 * dereference a value and optionally setting its type
 *
 * @param mixed $mixed
 * @param null  $type (optional)
 *
 * @return mixed $mixed set as $type
 */
function rettype($mixed, $type = NULL) {
    $type === NULL || settype($mixed, $type);
    return $mixed;
}

The usage example in your case (Online Demo):

$yourArray = Array('status' => 'Figure A. ...');

echo rettype($yourArray, 'object')->status; // prints "Figure A. ..."
Amir Koklan
  • 897
  • 2
  • 12
  • 32
hakre
  • 193,403
  • 52
  • 435
  • 836
25

You can use the (object) function to convert your array into an object.

$arr= [128=> ['status'=>
                 'Figure A. Facebook \'s horizontal scrollbars showing up on a 1024x768 screen resolution.'],
                  129=>['status'=>'The other day at work, I had some spare time']];

            $ArrToObject=(object)$arr;
            var_dump($ArrToObject);

The result will be an object that contains arrays:

object(stdClass)#1048 (2) { [128]=> array(1) {

["status"]=> string(87) "Figure A. Facebook 's horizontal scrollbars showing up on a 1024x768 screen resolution." }

[129]=> array(1) { ["status"]=> string(44) "The other day at work, I had some spare time" } }

Noha Shehab
  • 393
  • 5
  • 12
24

This one worked for me

  function array_to_obj($array, &$obj)
  {
    foreach ($array as $key => $value)
    {
      if (is_array($value))
      {
      $obj->$key = new stdClass();
      array_to_obj($value, $obj->$key);
      }
      else
      {
        $obj->$key = $value;
      }
    }
  return $obj;
  }

function arrayToObject($array)
{
 $object= new stdClass();
 return array_to_obj($array,$object);
}

usage :

$myobject = arrayToObject($array);
print_r($myobject);

returns :

    [127] => stdClass Object
        (
            [status] => Have you ever created a really great looking website design
        )

    [128] => stdClass Object
        (
            [status] => Figure A.
 Facebook's horizontal scrollbars showing up on a 1024x768 screen resolution.
        )

    [129] => stdClass Object
        (
            [status] => The other day at work, I had some spare time
        )

like usual you can loop it like:

foreach($myobject as $obj)
{
  echo $obj->status;
}
streetparade
  • 32,000
  • 37
  • 101
  • 123
20

There's no built-in method to do it as far as I'm aware, but it's as easy as a simple loop:

    $obj= new stdClass();

    foreach ($array as $k=> $v) {
        $obj->{$k} = $v;
    }

You can expound on that if you need it to build your object recursively.

zombat
  • 92,731
  • 24
  • 156
  • 164
11

Little complicated but easy to extend technique:

Suppose you have an array

$a = [
     'name' => 'ankit',
     'age' => '33',
     'dob' => '1984-04-12'
];

Suppose you have have a Person class which may have more or less attributes from this array. for example

class Person 
{
    private $name;
    private $dob;
    private $age;
    private $company;
    private $city;
}

If you still wanna change your array to the person object. You can use ArrayIterator Class.

$arrayIterator = new \ArrayIterator($a); // Pass your array in the argument.

Now you have iterator object.

Create a class extending FilterIterator Class; where you have to define the abstract method accept. Follow the example

class PersonIterator extends \FilterIterator
{
    public function accept()
    {
        return property_exists('Person', parent::current());
    }
}

The above impelmentation will bind the property only if it exists in the class.

Add one more method in the class PersonIterator

public function getObject(Person $object)
{
        foreach ($this as $key => $value)
        {
            $object->{'set' . underscoreToCamelCase($key)}($value);
        }
        return $object;
}

Make sure you have mutators defined in your class. Now you are ready to call these function where you want to create object.

$arrayiterator = new \ArrayIterator($a);
$personIterator = new \PersonIterator($arrayiterator);

$personIterator->getObject(); // this will return your Person Object. 
TimSparrow
  • 899
  • 11
  • 21
Ankit Vishwakarma
  • 1,573
  • 16
  • 13
11

Actually if you want to use this with multi-dimensional arrays you would want to use some recursion.

static public function array_to_object(array $array)
{
    foreach($array as $key => $value)
    {
        if(is_array($value))
        {
            $array[$key] = self::array_to_object($value);
        }
    }
    return (object)$array;
}
Nezzy
  • 191
  • 3
  • 8
10

I would definitly go with a clean way like this :

<?php

class Person {

  private $name;
  private $age;
  private $sexe;

  function __construct ($payload)
  {
     if (is_array($payload))
          $this->from_array($payload);
  }


  public function from_array($array)
  {
     foreach(get_object_vars($this) as $attrName => $attrValue)
        $this->{$attrName} = $array[$attrName];
  }

  public function say_hi ()
  {
     print "hi my name is {$this->name}";
  }
}

print_r($_POST);
$mike = new Person($_POST);
$mike->say_hi();

?>

if you submit:

formulaire

you will get this:

mike

I found this more logical comparing the above answers from Objects should be used for the purpose they've been made for (encapsulated cute little objects).

Also using get_object_vars ensure that no extra attributes are created in the manipulated Object (you don't want a car having a family name, nor a person behaving 4 wheels).

vdegenne
  • 12,272
  • 14
  • 80
  • 106
8

You could also use an ArrayObject, for example:

<?php
    $arr = array("test",
                 array("one"=>1,"two"=>2,"three"=>3), 
                 array("one"=>1,"two"=>2,"three"=>3)
           );
    $o = new ArrayObject($arr);
    echo $o->offsetGet(2)["two"],"\n";
    foreach ($o as $key=>$val){
        if (is_array($val)) {
            foreach($val as $k => $v) {
               echo $k . ' => ' . $v,"\n";
            }
        }
        else
        {
               echo $val,"\n";
        }
    }
?>

//Output:
  2
  test
  one => 1
  two => 2
  three => 3
  one => 1
  two => 2
  three => 3
slevy1
  • 3,797
  • 2
  • 27
  • 33
  • 1
    To my opinion this should become the best answer. More info herre: http://php.net/manual/en/arrayobject.construct.php – Julian May 29 '15 at 08:16
8

The one I use (it is a class member):

const MAX_LEVEL = 5; // change it as needed

public function arrayToObject($a, $level=0)
{

    if(!is_array($a)) {
        throw new InvalidArgumentException(sprintf('Type %s cannot be cast, array expected', gettype($a)));
    }

    if($level > self::MAX_LEVEL) {
        throw new OverflowException(sprintf('%s stack overflow: %d exceeds max recursion level', __METHOD__, $level));
    }

    $o = new stdClass();
    foreach($a as $key => $value) {
        if(is_array($value)) { // convert value recursively
            $value = $this->arrayToObject($value, $level+1);
        }
        $o->{$key} = $value;
    }
    return $o;
}
TimSparrow
  • 899
  • 11
  • 21
7

recursion is your friend:

function __toObject(Array $arr) {
    $obj = new stdClass();
    foreach($arr as $key=>$val) {
        if (is_array($val)) {
            $val = __toObject($val);
        }
        $obj->$key = $val;
    }

    return $obj;
}
MinhajulAnwar
  • 408
  • 6
  • 10
7

This requires PHP7 because I chose to use a lambda function to lock away the 'innerfunc' within the main function. The lambda function is called recursively, hence the need for: "use ( &$innerfunc )". You could do it in PHP5 but could not hide the innerfunc.

function convertArray2Object($defs) {
    $innerfunc = function ($a) use ( &$innerfunc ) {
       return (is_array($a)) ? (object) array_map($innerfunc, $a) : $a; 
    };
    return (object) array_map($innerfunc, $defs);
}
Chris Jeffries
  • 117
  • 2
  • 6
6

use this function that i've made:

function buildObject($class,$data){
    $object = new $class;
    foreach($data as $key=>$value){
        if(property_exists($class,$key)){
            $object->{'set'.ucfirst($key)}($value);
        }
    }
    return $object;
}

Usage:

$myObject = buildObject('MyClassName',$myArray);
Petter Friberg
  • 21,252
  • 9
  • 60
  • 109
Douraid Arfaoui
  • 212
  • 2
  • 6
6

one liner

$object= json_decode(json_encode($result_array, JSON_FORCE_OBJECT));
YesItsMe
  • 1,709
  • 16
  • 32
  • 1
    Note that references (e.g. to other arrays) stored in the original array will be duplicated by this one-liner. Say the key `x` in the array holds a reference to another array. Then `$object->x` after execution of your one-liner will be a duplicate of `$result_array['x']`, not the identical array. – The Coprolal Dec 13 '18 at 14:44
5

Easy:

$object = json_decode(json_encode($array));

Example:

$array = array(
    'key' => array(
        'k' => 'value',
    ),
    'group' => array('a', 'b', 'c')
);

$object = json_decode(json_encode($array));

Then, the following is true:

$object->key->k === 'value';
$object->group === array('a', 'b', 'c')
Eduardo Cuomo
  • 17,828
  • 6
  • 117
  • 94
  • 1
    I think this is a workaround. Why encode an array to json and then decode it? Its not an optimal decision to me. – Julian May 29 '15 at 08:32
  • 1
    @Julian, because it works recursively, does it in a properly defined and sufficiently reliable ("standard") way, and is also fast enough to be a good alternative to random hand-coded monkey magic. – Sz. Jul 27 '15 at 09:24
4

You could also do this by adding (object) on left of variable to create a new object.

<?php
$a = Array
    ( 'status' => " text" );
var_dump($a);
$b = (object)$a;
var_dump($b);
var_dump($b->status);

http://codepad.org/9YmD1KsU

fedmich
  • 5,343
  • 3
  • 37
  • 52
  • 1
    maybe worth mentioning this is called called "casting" or "type casting": http://www.php.net/manual/en/language.types.type-juggling.php#language.types.typecasting and behavior of (object)array() is documented here: http://www.php.net/manual/en/language.types.object.php#language.types.object.casting – Pete Jul 12 '13 at 19:58
4

Best Method in the WORLD :)

function arrayToObject($conArray)
{
    if(is_array($conArray)){
        /*
        * Return array converted to object
        * Using __FUNCTION__ (Magic constant)
        * for recursive call
        */
        return (object) array_map(__FUNCTION__, $conArray);
    }else{
        // Return object
        return $conArray;
    }
}

if you use different methods you will have problems. This is the best method. You have ever seen.

Zezeron
  • 57
  • 1
  • 4
3

Using json_encode is problematic because of the way that it handles non UTF-8 data. It's worth noting that the json_encode/json_encode method also leaves non-associative arrays as arrays. This may or may not be what you want. I was recently in the position of needing to recreate the functionality of this solution but without using json_ functions. Here's what I came up with:

/**
 * Returns true if the array has only integer keys
 */
function isArrayAssociative(array $array) {
    return (bool)count(array_filter(array_keys($array), 'is_string'));
}

/**
 * Converts an array to an object, but leaves non-associative arrays as arrays. 
 * This is the same logic that `json_decode(json_encode($arr), false)` uses.
 */
function arrayToObject(array $array, $maxDepth = 10) {
    if($maxDepth == 0) {
        return $array;
    }

    if(isArrayAssociative($array)) {
        $newObject = new \stdClass;
        foreach ($array as $key => $value) {
            if(is_array($value)) {
                $newObject->{$key} = arrayToObject($value, $maxDepth - 1);
            } else {
                $newObject->{$key} = $value;
            }
        }
        return $newObject;
    } else {

        $newArray = array();
        foreach ($array as $value) {
            if(is_array($value)) {
                $newArray[] = arrayToObject($value, $maxDepth - 1);
            } else {
                $newArray[] = $value;
            }                
        }
        return $newArray;
    }
}
DavidH
  • 1,420
  • 1
  • 14
  • 25
3

Multidimensional arrays into an object. this code is used for conversion of Bing search API try and catch method.

try {
        // Perform the Web request and get the JSON response
        $context = stream_context_create($options);
        $results = file_get_contents($url . "?cc=" . $country . "&category=" . $type, false, $context);
        $results = json_decode($results);
        return response()->json($results);
    } catch (\Exception $e) {
        $results = array('value' => array(
                (object) array(
                    "name" => "Unable to Retrive News",
                    "url" => "http://www.sample.com/",
                    "image" => (object) array("thumbnail" => (object) array("contentUrl" => "")),
                    "publishedAt" => "",
                    "description" => "")
            )
        );
        $results = (object) $results;
        return response()->json($results);
    }
3

You can use Reflection:

<?php

$array = ['name'=>'maria','age'=>33];

class Person {

    public $name;
    public $age;

    public function __construct(string $name, string $age){
        $this->name  = $name;
        $this->age = $age;
    }
}

function arrayToObject(array $array, string $class_name){

    $r = new ReflectionClass($class_name);
    $object = $r->newInstanceWithoutConstructor();
    $list = $r->getProperties();
    foreach($list as $prop){
      $prop->setAccessible(true);
      if(isset($array[$prop->name]))
        $prop->setValue($object, $array[$prop->name]);
    } 

    return $object;

}

$pessoa1 = arrayToObject($array, 'Person');
var_dump($pessoa1);
celsowm
  • 846
  • 9
  • 34
  • 59
2

Obviously just an extrapolation of some other folks' answers, but here's the recursive function that will convert any mulch-dimensional array into an object:

   function convert_array_to_object($array){
      $obj= new stdClass();
      foreach ($array as $k=> $v) {
         if (is_array($v)){
            $v = convert_array_to_object($v);   
         }
         $obj->{strtolower($k)} = $v;
      }
      return $obj;
   }

And remember that if the array had numeric keys they can still be referenced in the resulting object by using {} (for instance: $obj->prop->{4}->prop)

Ben D
  • 14,321
  • 3
  • 45
  • 59
1

Inspired by all these codes, i tried to create a enhanced version with support to: specific class name, avoid constructor method, 'beans' pattern and strict mode (set only existing properties):

    class Util {

static function arrayToObject($array, $class = 'stdClass', $strict = false) {
        if (!is_array($array)) {
            return $array;
        }

        //create an instance of an class without calling class's constructor
        $object = unserialize(
                sprintf(
                        'O:%d:"%s":0:{}', strlen($class), $class
                )
        );

        if (is_array($array) && count($array) > 0) {
            foreach ($array as $name => $value) {
                $name = strtolower(trim($name));
                if (!empty($name)) {

                    if(method_exists($object, 'set'.$name)){
                        $object->{'set'.$name}(Util::arrayToObject($value));
                    }else{
                        if(($strict)){

                            if(property_exists($class, $name)){

                                $object->$name = Util::arrayToObject($value); 

                            }

                        }else{
                            $object->$name = Util::arrayToObject($value); 
                        }

                    }

                }
            }
            return $object;
        } else {
            return FALSE;
        }
        }
}
celsowm
  • 846
  • 9
  • 34
  • 59
1

CakePHP has a recursive Set::map class that basically maps an array into an object. You may need to change what the array looks like in order to make the object look the way you want it.

http://api.cakephp.org/view_source/set/#line-158

Worst case, you may be able to get a few ideas from this function.

Dooltaz
  • 2,413
  • 1
  • 17
  • 16
1

Code

This function works as same as json_decode(json_encode($arr), false).

function arrayToObject(array $arr)
{
    $flat = array_keys($arr) === range(0, count($arr) - 1);
    $out = $flat ? [] : new \stdClass();

    foreach ($arr as $key => $value) {
        $temp = is_array($value) ? $this->arrayToObject($value) : $value;

        if ($flat) {
            $out[] = $temp;
        } else {
            $out->{$key} = $temp;
        }
    }

    return $out;
}

Testing

Test 1: Flat array

$arr = ["a", "b", "c"];
var_export(json_decode(json_encode($arr)));
var_export($this->arrayToObject($arr));

Output:

array(
    0 => 'a',
    1 => 'b',
    2 => 'c',
)
array(
    0 => 'a',
    1 => 'b',
    2 => 'c',
)

Test 2: Array of objects

$arr = [["a" => 1], ["a" => 1], ["a" => 1]];
var_export(json_decode(json_encode($arr)));
var_export($this->arrayToObject($arr));

Output:

array(
    0 => stdClass::__set_state(array('a' => 1,)),
    1 => stdClass::__set_state(array('a' => 1,)),
    2 => stdClass::__set_state(array('a' => 1,)),
)
array(
    0 => stdClass::__set_state(array('a' => 1,)),
    1 => stdClass::__set_state(array('a' => 1,)),
    2 => stdClass::__set_state(array('a' => 1,)),
)

Test 3: Object

$arr = ["a" => 1];
var_export(json_decode($arr));
var_export($this->arrayToObject($arr));

Output:

stdClass::__set_state(array('a' => 1,))
stdClass::__set_state(array('a' => 1,))
acelot
  • 752
  • 2
  • 7
  • 26
0

i have done it with quite simple way,

    $list_years         = array();
    $object             = new stdClass();

    $object->year_id   = 1 ;
    $object->year_name = 2001 ;
    $list_years[]       = $object;
Muhammad
  • 3,169
  • 5
  • 41
  • 70
0
function object_to_array($data)
{
    if (is_array($data) || is_object($data))
    {
        $result = array();
        foreach ($data as $key => $value)
        {
            $result[$key] = object_to_array($value);
        }
        return $result;
    }
    return $data;
}

function array_to_object($data)
{
    if (is_array($data) || is_object($data))
    {
        $result= new stdClass();
        foreach ($data as $key => $value)
        {
            $result->$key = array_to_object($value);
        }
        return $result;
    }
    return $data;
}
daniula
  • 6,898
  • 4
  • 32
  • 49
0

By using (array) and (object) as prefix, you can simply convert object array to standard array and vice-verse

<?php
//defining an array
$a = array('a'=>'1','b'=>'2','c'=>'3','d'=>'4');

//defining an object array
$obj = new stdClass();
$obj->a = '1';
$obj->b = '2';
$obj->c = '3';
$obj->d = '4';

print_r($a);echo '<br>';
print_r($obj);echo '<br>';

//converting object array to array
$b = (array) $obj;
print_r($b);echo '<br>';

//converting array to object
$c = (object) $a;
print_r($c);echo '<br>';
?>
VishnuPrasad
  • 1,078
  • 5
  • 17
  • 36
0

I use the following to parse Yaml files associative arrays into an object state.

This checks all supplied arrays if there are objects hiding there, and turns them also in objects.

    /**
     * Makes a config object from an array, making the first level keys properties a new object.
     * Property values are converted to camelCase and are not set if one already exists.
     * @param array $configArray Config array.
     * @param boolean $strict To return an empty object if $configArray is not an array
     * @return stdObject The config object
     */
    public function makeConfigFromArray($configArray = [],$strict = true)
    {
        $object = new stdClass();

        if (!is_array($configArray)) {
            if(!$strict && !is_null($configArray)) {
                return $configArray;
            }
            return $object;
        }

        foreach ($configArray as $name => $value) {
            $_name = camel_case($name);
            if(is_array($value)) {
                $makeobject = true;
                foreach($value as $key => $val) {
                    if(is_numeric(substr($key,0,1))) {
                        $makeobject = false;
                    }
                    if(is_array($val)) {
                        $value[$key] = $this->makeConfigFromArray($val,false);
                    }
                }
                if($makeobject) {
                    $object->{$name} = $object->{$_name} = $this->makeConfigFromArray($value,false);
                }
                else {
                    $object->{$name} = $object->{$_name} = $value;
                }

            }
            else {
                $object->{$name} = $object->{$_name} = $value;
            }
        }

        return $object;
    }

This turns a yaml configured as

fields:
    abc:
        type: formfield
        something:
            - a
            - b
            - c
            - d:
                foo: 
                   bar

to an array consisting of:

array:1 [
  "fields" => array:1 [
    "abc" => array:2 [
      "type" => "formfield"
      "something" => array:4 [
        0 => "a"
        1 => "b"
        2 => "c"
        3 => array:1 [
          "d" => array:1 [
            "foo" => "bar"
          ]
        ]
      ]
    ]
  ]
]

to an object of:

{#325
  +"fields": {#326
    +"abc": {#324
      +"type": "formfield"
      +"something": array:4 [
        0 => "a"
        1 => "b"
        2 => "c"
        3 => {#328
          +"d": {#327
            +"foo": "bar"
          }
        }
      ]
    }
  }
}
Tschallacka
  • 27,901
  • 14
  • 88
  • 133
0

If you need to cast an array to a specific class (as in my case I need the object to be of type Google_Service_AndroidPublisher_Resource_Inappproducts for my mock), you can str_replace the class name from stdClass to the intended class like this:

function castArrayToClass(array $array, string $className)
{
    //first cast the array to stdClass
    $subject = serialize((object)$array);
    //then change the class name
    $converted = str_replace(
        'O:8:"stdClass"',
        'O:'.strlen($className).':"'.$className.'"',
        $subject
    );
    unset($subject);

    return unserialize($converted);
}
PHZ.fi-Pharazon
  • 1,479
  • 14
  • 15