php stdClass 到数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18576762/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
php stdClass to array
提问by Alessandro Minoccheri
I have a problem to convert an object stdClass to array. I have tried in this way:
我在将对象 stdClass 转换为数组时遇到问题。我已经尝试过这种方式:
return (array) $booking;
or
或者
return (array) json_decode($booking,true);
or
或者
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 before cast:
转换前的数组:
array(1) { [0]=> object(stdClass)#23 (36) { ["id"]=> string(1) "2" ["name"]=> string(0) "" ["code"]=> string(5) "56/13" } }
after cast is empty NULL if I try to make a var_dump($booking);
如果我尝试制作一个,则转换后为空 NULL 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;
}
}
回答by h2ooooooo
The lazyone-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 方法在单行中执行此操作(尽管有些人报告说它比递归遍历对象更快 - 很可能是因为 PHP在调用函数时速度很慢)。“但我已经这样做了”你说。不完全是 - 您json_decode
在数组上使用过,但您需要先对其进行编码json_encode
。
Requirements
要求
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 reallyupdate your PHP installation. Support for 5.1 stopped in 2006.)
该json_encode
和json_decode
方法。这些在 PHP 5.2.0 及更高版本中自动捆绑。如果您使用任何旧版本,还有一个PECL 库(也就是说,在这种情况下,您应该真正更新您的 PHP 安装。2006 年停止支持 5.1。)
Converting an array
/stdClass
-> stdClass
转换array
/ stdClass
->stdClass
$stdClass = json_decode(json_encode($booking));
Converting an array
/stdClass
-> array
转换array
/ stdClass
->array
The manual specifies the second argument of json_decode
as:
该手册指定了json_decode
as的第二个参数:
assoc
WhenTRUE
, returned objects will be converted into associative arrays.
assoc
时TRUE
,返回的对象将转换为关联数组。
Hence the following line will convert your entire object into an array:
因此,以下行会将您的整个对象转换为数组:
$array = json_decode(json_encode($booking), true);
回答by robzero
use this function to get a standard array back of the type you are after...
使用此函数来获取您所追求的类型的标准数组...
return get_object_vars($booking);
回答by Vlad Preda
Since it's an array before you cast it, casting it makes no sense.
由于它是在您投射之前的数组,因此投射它是没有意义的。
You may want a recursive cast, which would look something like this:
您可能需要递归转换,它看起来像这样:
function arrayCastRecursive($array)
{
if (is_array($array)) {
foreach ($array as $key => $value) {
if (is_array($value)) {
$array[$key] = arrayCastRecursive($value);
}
if ($value instanceof stdClass) {
$array[$key] = arrayCastRecursive((array)$value);
}
}
}
if ($array instanceof stdClass) {
return arrayCastRecursive((array)$array);
}
return $array;
}
Usage:
用法:
$obj = new stdClass;
$obj->aaa = 'asdf';
$obj->bbb = 'adsf43';
$arr = array('asdf', array($obj, 3));
var_dump($arr);
$arr = arrayCastRecursive($arr);
var_dump($arr);
Result before:
之前的结果:
array
0 => string 'asdf' (length = 4)
1 =>
array
0 =>
object(stdClass)[1]
public 'aaa' => string 'asdf' (length = 4)
public 'bbb' => string 'adsf43' (length = 6)
1 => int 3
Result after:
之后的结果:
array
0 => string 'asdf' (length = 4)
1 =>
array
0 =>
array
'aaa' => string 'asdf' (length = 4)
'bbb' => string 'adsf43' (length = 6)
1 => int 3
Note:
笔记:
Tested and working with complex arrays where a stdClass object can contain other stdClass objects.
测试并使用复杂数组,其中 stdClass 对象可以包含其他 stdClass 对象。
回答by Nalantha
Please use following php function to convert php stdClass to array
请使用以下 php 函数将 php stdClass 转换为数组
get_object_vars($data)
回答by Carlo Fontanos
This function worked for me:
这个功能对我有用:
function cvf_convert_object_to_array($data) {
if (is_object($data)) {
$data = get_object_vars($data);
}
if (is_array($data)) {
return array_map(__FUNCTION__, $data);
}
else {
return $data;
}
}
Reference: http://carlofontanos.com/convert-stdclass-object-to-array-in-php/
参考:http: //carlofontanos.com/convert-stdclass-object-to-array-in-php/
回答by David Clews
Use the built in type cast functionality, simply type
使用内置的类型转换功能,只需键入
$realArray = (array)$stdClass;
回答by shasi kanth
Just googled it, and found herea handy function that is useful for converting stdClass object to array recursively.
刚刚在 google 上搜索了一下,发现这里有一个方便的函数,可用于将 stdClass 对象递归地转换为数组。
<?php
function object_to_array($object) {
if (is_object($object)) {
return array_map(__FUNCTION__, get_object_vars($object));
} else if (is_array($object)) {
return array_map(__FUNCTION__, $object);
} else {
return $object;
}
}
?>
EDIT: I updated this answer with content from linked source (which is also changed now), thanks to mason81 for suggesting me.
编辑:我用链接源的内容更新了这个答案(现在也改变了),感谢 mason81 的建议。
回答by Loren
Here is a version of Carlo's answer that can be used in a class:
这是可在课堂上使用的 Carlo 答案的一个版本:
class Formatter
{
public function objectToArray($data)
{
if (is_object($data)) {
$data = get_object_vars($data);
}
if (is_array($data)) {
return array_map(array($this, 'objectToArray'), $data);
}
return $data;
}
}
回答by walter1957
The following code will read all emails & print the Subject, Body & Date.
以下代码将读取所有电子邮件并打印主题、正文和日期。
<?php
$imap=imap_open("Mailbox","Email Address","Password");
if($imap){$fixMessages=1+imap_num_msg($imap); //Check no.of.msgs
/*
By adding 1 to "imap_num_msg($imap)" & starting at $count=1
the "Start" & "End" non-messages are ignored
*/
for ($count=1; $count<$fixMessages; $count++){
$objectOverview=imap_fetch_overview($imap,$count,0);
print '<br>$objectOverview: '; print_r($objectOverview);
print '<br>objectSubject ='.($objectOverview[0]->subject));
print '<br>objectDate ='.($objectOverview[0]->date);
$bodyMessage=imap_fetchbody($imap,$count,1);
print '<br>bodyMessage ='.$bodyMessage.'<br><br>';
} //for ($count=1; $count<$fixMessages; $count++)
} //if($imap)
imap_close($imap);
?>
This outputs the following:
这将输出以下内容:
$objectOverview: Array ( [0] => stdClass Object ( [subject] => Hello
[from] => Email Address [to] => Email Address [date] => Sun, 16 Jul 2017 20:23:18 +0100
[message_id] => [size] => 741 [uid] => 2 [msgno] => 2 [recent] => 0 [flagged] => 0
[answered] => 0 [deleted] => 0 [seen] => 1 [draft] => 0 [udate] => 1500232998 ) )
objectSubject =Hello
objectDate =Sun, 16 Jul 2017 20:23:18 +0100
bodyMessage =Test
Having struggled with various suggestions I have used trial & error to come up with this solution. Hope it helps.
在与各种建议作斗争后,我使用反复试验来提出这个解决方案。希望能帮助到你。
回答by nsdb
Here is the best Object to Array function I have - works recursively:
这是我拥有的最好的 Object to Array 函数 - 递归工作:
function object_to_array($obj, &$arr){
if(!is_object($obj) && !is_array($obj)){
$arr = $obj;
return $arr;
}
foreach ($obj as $key => $value)
{
if (!empty($value))
{
$arr[$key] = array();
object_to_array_v2($value, $arr[$key]);
}
else
{
$arr[$key] = $value;
}
}
return $arr;
}
$clean_array = object_to_array($object_data_here);
$clean_array = object_to_array($object_data_here);