<?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
)...
)
这可能吗?
//My Function is worked. Hope help full for you :)
$input = [
'1' => (object) [1,2,3],
'2' => (object) [4,5,6,
(object) [6,7,8,
[9, 10, 11,
(object) [12, 13, 14]]]
],
'3' =>[15, 16, (object)[17, 18]]
];
echo "<pre>";
var_dump($input);
var_dump(toAnArray($input));
public function toAnArray(&$input) {
if (is_object($input)) {
$input = get_object_vars($input);
}
foreach ($input as &$item) {
if (is_object($item) || is_array($item)) {
if (is_object($item)) {
$item = get_object_vars($item);
}
self::toAnArray($item);
}
}
}
//My Function is worked. Hope help full for you :)
$input = [
'1' => (object) [1,2,3],
'2' => (object) [4,5,6,
(object) [6,7,8,
[9, 10, 11,
(object) [12, 13, 14]]]
],
'3' =>[15, 16, (object)[17, 18]]
];
echo "<pre>";
var_dump($input);
var_dump(toAnArray($input));
public function toAnArray(&$input) {
if (is_object($input)) {
$input = get_object_vars($input);
}
foreach ($input as &$item) {
if (is_object($item) || is_array($item)) {
if (is_object($item)) {
$item = get_object_vars($item);
}
self::toAnArray($item);
}
}
}
注意:
$array = (array) $object;
做一个浅转换($object->innerObject = new stdClass()仍然是一个对象)和来回转换使用json工作,但这不是一个好主意,如果性能是一个问题。
如果你需要将所有对象转换为关联数组,这里是一个更好的方法(代码摘自我不记得在哪里):
function toArray($obj)
{
if (is_object($obj)) $obj = (array)$obj;
if (is_array($obj)) {
$new = array();
foreach ($obj as $key => $val) {
$new[$key] = toArray($val);
}
} else {
$new = $obj;
}
return $new;
}