<?php
   print_r($response->response->docs);
?>

输出如下:

    Array 
(
    [0] => Object 
            (
                [_fields:private] => Array 
                                    (
                                        [id]=>9093 
                                        [name]=>zahir
                                    ) 
            Object 
            ( 
                [_fields:private] => Array 
                                    (
                                        [id]=>9094 
                                        [name]=>hussain
                                    )..
            )
)

如何将此对象转换为数组?我想输出以下内容:

Array
(
    [0]=>
    (
        [id]=>9093 
        [name]=>zahir
    ) 
    [1]=>
    (
        [id]=>9094 
        [name]=>hussain
    )...
)

这可能吗?


当前回答

你应该看看get_object_vars,因为你的属性是私有的,你应该在类中调用它并返回它的结果。

小心,对于像字符串这样的原始数据类型,它会工作得很好,但我不知道它对嵌套对象如何表现。

在你的情况下,你必须这样做;

<?php
   print_r(get_object_vars($response->response->docs));
?>

其他回答

我有同样的问题,我解决了上面提到的get_object_vars。

此外,我必须使用json_decode转换我的对象,并且必须使用老式的“for”循环(而不是for-each)迭代数组。

$array = json_decode(json_encode($object), true);

我尝试了几种方法来做一个对象的foreach,这真的是我所见过的最简单和最酷的方法。只有一行:)

通过依赖JSON编码/解码函数的行为,可以快速将深度嵌套的对象转换为关联数组:

$array = json_decode(json_encode($response->response->docs), true);

试试这个:

 <?php
  print_r(json_decode(json_encode($response->response->docs),true));
 ?>

你也可以使用php的array_values()方法