如何将这样的数组转换为对象?
[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"
)
当前回答
实际上,如果你想在多维数组中使用这个你就需要使用一些递归。
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;
}
其他回答
这里有三种方法:
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; }
我用了很简单的方法,
$list_years = array();
$object = new stdClass();
$object->year_id = 1 ;
$object->year_name = 2001 ;
$list_years[] = $object;
世界上最好的方法:)
function arrayToObject($conArray)
{
if(is_array($conArray)){
/*
* Return array converted to object
* Using __FUNCTION__ (Magic constant)
* for recursive call
*/
return (object) array_map(__FUNCTION__, $conArray);
}else{
// Return object
return $conArray;
}
}
如果使用不同的方法,就会出现问题。这是最好的方法。你所见过的。
你可以使用反射:
<?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
最坏的情况下,您可能会从这个函数中得到一些想法。