如何将这样的数组转换为对象?
[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;
}
其他回答
世界上最好的方法:)
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;
}
}
如果使用不同的方法,就会出现问题。这是最好的方法。你所见过的。
我使用的一个(它是类成员):
const MAX_LEVEL = 5; // change it as needed
public function arrayToObject($a, $level=0)
{
if(!is_array($a)) {
throw new InvalidArgumentException(sprintf('Type %s cannot be cast, array expected', gettype($a)));
}
if($level > self::MAX_LEVEL) {
throw new OverflowException(sprintf('%s stack overflow: %d exceeds max recursion level', __METHOD__, $level));
}
$o = new stdClass();
foreach($a as $key => $value) {
if(is_array($value)) { // convert value recursively
$value = $this->arrayToObject($value, $level+1);
}
$o->{$key} = $value;
}
return $o;
}
这里有三种方法:
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; }
这需要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);
}
CakePHP有一个递归的Set::map类,基本上是将数组映射到对象。为了使对象看起来像你想要的样子,你可能需要改变数组的样子。
http://api.cakephp.org/view_source/set/#line-158
最坏的情况下,您可能会从这个函数中得到一些想法。