如何将这样的数组转换为对象?
[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"
)
当前回答
使用我创建的这个函数:
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
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();
?>
如果你提交:
你会得到这个:
我发现这更符合逻辑的比较以上的答案从对象应该用于他们的目的(封装可爱的小对象)。
此外,使用get_object_vars确保在被操纵的对象中没有创建额外的属性(您不希望汽车有姓,也不希望人有4个轮子)。
简单的方法是
$object = (object)$array;
但这不是你想要的。如果你想要对象,你想要实现一些东西,但这在这个问题中是缺失的。仅仅为了使用对象而使用对象是没有意义的。
这里有三种方法:
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; }
快速攻击:
// assuming $var is a multidimensional array
$obj = json_decode (json_encode ($var), FALSE);
不漂亮,但很好用。
如果你需要将一个数组强制转换为一个特定的类(在我的例子中,我需要对象类型为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);
}