如何将这样的数组转换为对象?
[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"
)
当前回答
容易:
$object = json_decode(json_encode($array));
例子:
$array = array(
'key' => array(
'k' => 'value',
),
'group' => array('a', 'b', 'c')
);
$object = json_decode(json_encode($array));
那么,以下是正确的:
$object->key->k === 'value';
$object->group === array('a', 'b', 'c')
其他回答
容易:
$object = json_decode(json_encode($array));
例子:
$array = array(
'key' => array(
'k' => 'value',
),
'group' => array('a', 'b', 'c')
);
$object = json_decode(json_encode($array));
那么,以下是正确的:
$object->key->k === 'value';
$object->group === array('a', 'b', 'c')
递归是你的朋友:
function __toObject(Array $arr) {
$obj = new stdClass();
foreach($arr as $key=>$val) {
if (is_array($val)) {
$val = __toObject($val);
}
$obj->$key = $val;
}
return $obj;
}
一个衬套
$object= json_decode(json_encode($result_array, JSON_FORCE_OBJECT));
快速攻击:
// assuming $var is a multidimensional array
$obj = json_decode (json_encode ($var), FALSE);
不漂亮,但很好用。
我也有这个问题,但我注意到json_decode将JSON数组转换为对象。
所以,我通过使用json_encode($PHPArray)来实现我的解决方案,它返回对象的JSON字符串,然后我用Json_decode($string)解码字符串,它将返回一个完美的结构化对象。 速记
$object = json_decode(json_encode($array));
Or
$jsonString = json_encode($array);
$object = json_decode($jsonString);