response->docs);
?>
Outputs the following:
Array
(
[0] => Object
(
You can quickly convert deeply nested objects to associative arrays by relying on the behavior of the JSON encode/decode functions:
$array = json_decode(json_encode($response->response->docs), true);
You should look at get_object_vars , as your properties are declared private you should call this inside the class and return its results.
Be careful, for primitive data types like strings it will work great, but I don't know how it behaves with nested objects.
in your case you have to do something like;
<?php
print_r(get_object_vars($response->response->docs));
?>
Careful:
$array = (array) $object;
does a shallow conversion ($object->innerObject = new stdClass() remains an object) and converting back and forth using json works but it's not a good idea if performance is an issue.
If you need all objects to be converted to associative arrays here is a better way to do that (code ripped from I don't remember where):
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;
}
Simple version:
$arrayObject = new ArrayObject($object);
$array = $arrayObject->getArrayCopy();
Updated recursive version:
class RecursiveArrayObject extends ArrayObject
{
function getArrayCopy()
{
$resultArray = parent::getArrayCopy();
foreach($resultArray as $key => $val) {
if (!is_object($val)) {
continue;
}
$o = new RecursiveArrayObject($val);
$resultArray[$key] = $o->getArrayCopy();
}
return $resultArray;
}
}
$arrayObject = new RecursiveArrayObject($object);
$array = $arrayObject->getArrayCopy();
//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);
}
}
}