如何将这样的数组转换为对象?
[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"
)
当前回答
这需要PHP7,因为我选择使用lambda函数来锁定主函数中的'innerfunc'。lambda函数是递归调用的,因此需要:"use (&$innerfunc)"。你可以在PHP5中这样做,但不能隐藏innerfunc。
function convertArray2Object($defs) {
$innerfunc = function ($a) use ( &$innerfunc ) {
return (is_array($a)) ? (object) array_map($innerfunc, $a) : $a;
};
return (object) array_map($innerfunc, $defs);
}
其他回答
实际上,如果你想在多维数组中使用这个你就需要使用一些递归。
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;
}
您可以简单地使用类型强制转换将数组转换为对象。
// *convert array to object* Array([id]=> 321313[username]=>shahbaz)
$object = (object) $array_name;
//now it is converted to object and you can access it.
echo $object->username;
一个衬套
$object= json_decode(json_encode($result_array, JSON_FORCE_OBJECT));
如果你需要将一个数组强制转换为一个特定的类(在我的例子中,我需要对象类型为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