How to convert an array to object in PHP?

我如何将这样的数组转换为对象?

    [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
        )

)

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


您可以简单地使用类型转换将数组转换为对象。

// *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;

Here are three ways:

  • 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;
        }
    }
    
  • Convert the array into an object by casting it to an object:

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

    $object = object;
    foreach ($arr as $key => $value) {
        $object->{$key} = $value;
    }
    
  • 链接地址: http://www.djcxy.com/p/23644.html

    上一篇: JavaScript对象:按字符串名称访问变量属性

    下一篇: 如何将数组转换为PHP中的对象?