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

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

当前回答

你也可以通过在变量的左边添加(object)来创建一个新对象。

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

http://codepad.org/9YmD1KsU

其他回答

你可以使用反射:

<?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);

实际上,如果你想在多维数组中使用这个你就需要使用一些递归。

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

如果你需要将一个数组强制转换为一个特定的类(在我的例子中,我需要对象类型为Google_Service_AndroidPublisher_Resource_Inappproducts),你可以像这样从stdClass中将类名str_replace为预期的类:

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

你也可以通过在变量的左边添加(object)来创建一个新对象。

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

http://codepad.org/9YmD1KsU

简单的方法是

$object = (object)$array;

但这不是你想要的。如果你想要对象,你想要实现一些东西,但这在这个问题中是缺失的。仅仅为了使用对象而使用对象是没有意义的。