如何将这样的数组转换为对象?
[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"
)
如何将这样的数组转换为对象?
[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"
)
当前回答
如果你需要将一个数组强制转换为一个特定的类(在我的例子中,我需要对象类型为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);
}
其他回答
我用了很简单的方法,
$list_years = array();
$object = new stdClass();
$object->year_id = 1 ;
$object->year_name = 2001 ;
$list_years[] = $object;
据我所知,没有内置的方法可以做到这一点,但它就像一个简单的循环一样简单:
$obj= new stdClass();
foreach ($array as $k=> $v) {
$obj->{$k} = $v;
}
如果你需要递归地构建你的对象,你可以详细说明。
使用我创建的这个函数:
function buildObject($class,$data){
$object = new $class;
foreach($data as $key=>$value){
if(property_exists($class,$key)){
$object->{'set'.ucfirst($key)}($value);
}
}
return $object;
}
用法:
$myObject = buildObject('MyClassName',$myArray);
你可以使用反射:
<?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);
CakePHP有一个递归的Set::map类,基本上是将数组映射到对象。为了使对象看起来像你想要的样子,你可能需要改变数组的样子。
http://api.cakephp.org/view_source/set/#line-158
最坏的情况下,您可能会从这个函数中得到一些想法。