php stdClass 到数组 [英] php stdClass to array
问题描述
我在将对象 stdClass 转换为数组时遇到问题.我是这样试的:
I have a problem to convert an object stdClass to array. I have tried in this way:
return (array) $booking;
或
return (array) json_decode($booking,true);
或
return (array) json_decode($booking);
转换前的数组只有一个记录,在我尝试转换后它是空的.如何在不删除其行的情况下对其进行转换/转换?
The array before the cast is full with one record, after my try to cast it is empty. How to cast / convert it without delete its rows?
转换前的数组:
array(1) { [0]=> object(stdClass)#23 (36) { ["id"]=> string(1) "2" ["name"]=> string(0) "" ["code"]=> string(5) "56/13" } }
如果我尝试创建一个 var_dump($booking);
我也试过这个功能,但总是空的:
I have also tried this function but always empty:
public function objectToArray($d) {
if (is_object($d)) {
// Gets the properties of the given object
// with get_object_vars function
$d = get_object_vars($d);
}
if (is_array($d)) {
/*
* Return array converted to object
* Using __FUNCTION__ (Magic constant)
* for recursive call
*/
return array_map(__FUNCTION__, $d);
}
else {
// Return array
return $d;
}
}
推荐答案
lazy 单行方法
如果您愿意损失一点点性能,您可以使用 JSON 方法在单行中执行此操作(尽管有些人报告说它比递归遍历对象更快 - 很可能是因为 PHP 是 调用函数很慢).但我已经这样做了"你说.不完全是 - 您在数组上使用了 json_decode
,但您需要对其进行编码首先使用 json_encode
.
The lazy one-liner method
You can do this in a one liner using the JSON methods if you're willing to lose a tiny bit of performance (though some have reported it being faster than iterating through the objects recursively - most likely because PHP is slow at calling functions). "But I already did this" you say. Not exactly - you used json_decode
on the array, but you need to encode it with json_encode
first.
json_encode
和 json_decode
方法.这些在 PHP 5.2.0 及更高版本中自动捆绑.如果您使用任何旧版本,还有一个 PECL 库(也就是说,在这种情况下,您应该真的更新您的 PHP 安装.2006 年停止支持 5.1.)
The json_encode
and json_decode
methods. These are automatically bundled in PHP 5.2.0 and up. If you use any older version there's also a PECL library (that said, in that case you should really update your PHP installation. Support for 5.1 stopped in 2006.)
$stdClass = json_decode(json_encode($booking));
<小时>
转换array
/stdClass
-> array
手册将json_decode
的第二个参数指定为:
Converting an array
/stdClass
-> array
The manual specifies the second argument of json_decode
as:
关联
当TRUE
时,返回的对象将转换为关联数组.
assoc
WhenTRUE
, returned objects will be converted into associative arrays.
因此,以下行会将您的整个对象转换为数组:
Hence the following line will convert your entire object into an array:
$array = json_decode(json_encode($booking), true);
这篇关于php stdClass 到数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!