How do I convert an object to an array?

Php

Php Problem Overview


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

Outputs the following:

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

How can I convert this object to an array? I'd like to output the following:

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

Is this possible?

Php Solutions


Solution 1 - Php

Single-dimensional arrays

For converting single-dimension arrays, you can cast using (array) or there's get_object_vars, which Benoit mentioned in his answer.

// Cast to an array
$array = (array) $object;

// get_object_vars
$array = get_object_vars($object);

They work slightly different from each other. For example, get_object_vars will return an array with only publicly accessible properties unless it is called from within the scope of the object you're passing (ie in a member function of the object). (array), on the other hand, will cast to an array with all public, private and protected members intact on the array, though all public now, of course.

Multi-dimensional arrays

A somewhat dirty method is to use PHP >= 5.2's native JSON functions to encode to JSON and then decode back to an array. This will not include private and protected members, however, and is not suitable for objects that contain data that cannot be JSON encoded (such as binary data).

// The second parameter of json_decode forces parsing into an associative array
$array = json_decode(json_encode($object), true);

Alternatively, the following function will convert from an object to an array including private and protected members, taken from here and modified to use casting:

function objectToArray ($object) {
    if(!is_object($object) && !is_array($object))
        return $object;

    return array_map('objectToArray', (array) $object);
}

Solution 2 - Php

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));
?>

Solution 3 - Php

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);

Solution 4 - Php

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;
}

Solution 5 - Php

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

I tried several ways to do a foreach with an object and THIS really is the most easy and cool workaround I have seen. Just one line :)

Solution 6 - Php

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();

Solution 7 - Php

Try this:-

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

Solution 8 - Php

I had the same problem and I solved it with get_object_vars mentioned above.

Furthermore, I had to convert my object with json_decode and I had to iterate the array with the oldschool "for" loop (rather then for-each).

Solution 9 - Php

I ran into an issue with Andy Earnshaw's answer because I had factored this function out to a separate class within my application, "HelperFunctions", which meant the recursive call to objectToArray() failed.

I overcame this by specifying the class name within the array_map call like so:

public function objectToArray($object) {
	if (!is_object($object) && !is_array($object))
		return $object;
	return array_map(array("HelperFunctions", "objectToArray"), (array) $object);
}

I would have written this in the comments but I don't have enough reputation yet.

Solution 10 - Php

You can also use array_values() method of php

Solution 11 - Php

//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);
            }
        }
    }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionzahir hussain View Question on Stackoverflow
Solution 1 - PhpAndy EView Answer on Stackoverflow
Solution 2 - PhpBenoitView Answer on Stackoverflow
Solution 3 - PhpMufaddalView Answer on Stackoverflow
Solution 4 - PhpSergioView Answer on Stackoverflow
Solution 5 - Phpm3ndaView Answer on Stackoverflow
Solution 6 - PhpStyxView Answer on Stackoverflow
Solution 7 - PhpkunalView Answer on Stackoverflow
Solution 8 - PhpLucas BacciottiView Answer on Stackoverflow
Solution 9 - Phpleon.clementsView Answer on Stackoverflow
Solution 10 - PhpRikin AdhyapakView Answer on Stackoverflow
Solution 11 - Phpnguyentrung206View Answer on Stackoverflow