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

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

当前回答

有点复杂,但很容易扩展的技术:

假设你有一个数组

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

假设您有一个Person类,它可能有来自这个数组的或多或少的属性。例如

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

如果你还想把数组改成person对象。你可以使用ArrayIterator类。

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

现在你有了迭代器对象。

创建一个扩展FilterIterator class的类;你必须定义抽象方法accept。遵循示例

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

上面的实现只在类中存在该属性时才会绑定它。

在类PersonIterator中再添加一个方法

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

确保在类中定义了mutator。 现在,您可以在想要创建对象的地方调用这些函数。

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

$personIterator->getObject(); // this will return your Person Object. 

其他回答

据我所知,没有内置的方法可以做到这一点,但它就像一个简单的循环一样简单:

    $obj= new stdClass();

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

如果你需要递归地构建你的对象,你可以详细说明。

它的方法很简单,这将为递归数组创建一个对象:

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

可以使用(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);

结果将是一个包含数组的对象:

对象(stdClass)#1048(2){[128]=>数组(1){ ["地位"]= > 字符串(87)“图a: Facebook的水平滚动条显示在1024x768分辨率的屏幕上。”} [129]=>数组(1){ ["地位"]= > 字符串(44)“前几天上班,我有一些空闲时间”}}

我使用以下代码将Yaml文件关联数组解析为对象状态。

这将检查所有提供的数组中是否隐藏有对象,并将它们转换为对象。

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

这将把yaml配置为

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

到由以下数组组成的数组:

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"
          ]
        ]
      ]
    ]
  ]
]

以…为目标:

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

如果你需要将一个数组强制转换为一个特定的类(在我的例子中,我需要对象类型为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);
}