209
<?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?

Ahmed Syed
  • 1,179
  • 2
  • 18
  • 44
zahir hussain
  • 3,711
  • 10
  • 29
  • 36

11 Answers11

392

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);
}
Andy E
  • 338,112
  • 86
  • 474
  • 445
  • 5
    First solution didn't handle mutlidimensions, but second solution worked great. – sbuck Jan 27 '12 at 04:10
  • 1
    2nd solution reminded me there is a 2nd parameter to json_decode() which I forgot.. thanks. – Tyler Feb 07 '13 at 02:59
  • 1
    I wonder why this answer is getting so many votes. Both solutions are less clear and pretty than get_object_vars – RJD22 Feb 28 '13 at 13:46
  • 3
    @RJD22: I've updated my answer to make it more of a 'de facto' resource, hopefully you regard it as worthy of its up votes now. ;-) Note to everyone else that the "2nd solution" the comments refer to here is the JSON solution, which was the 2nd in my first answer. – Andy E Mar 21 '13 at 09:46
  • AWESOME! I was amazed by a solution and scrolled down to find this! – eozzy Sep 07 '16 at 06:22
  • @RJD22 get_object_vars will not include private members, whereas casting to array will (with a strange class prefix). Depending on your use case, they are not equivalent. – Saeven Nov 25 '20 at 18:30
137

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));
?>
Ahmed Syed
  • 1,179
  • 2
  • 18
  • 44
Benoit
  • 3,569
  • 2
  • 22
  • 20
45

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);
Mufaddal
  • 5,398
  • 7
  • 42
  • 57
  • 2
    This is the most simple answer to this problem. Used it and it worked awesome. Thanks – Dustin Fraker Jul 28 '13 at 15:59
  • 7
    Just a note - this will work in case your array contains UTF8 valid data. If your array contains some other encoding, let say Win1250, it will fail, as json_encode will fail (php 5.3) – Radek Dec 03 '13 at 14:40
  • How to convert it back to an object? – Peyman Mohamadpour Jan 20 '17 at 08:40
  • @Trix use json again json_decode(json_encode($array), FALSE);This also (recursively) converts all of your sub arrays into objects, – Mufaddal Jan 20 '17 at 12:32
  • I wish I could uptick this more than once. – JohnFF Jun 20 '17 at 17:20
  • @galdikas sure. As you can see both [`json_encode()` (PHP 5 >= 5.2.0, PECL json >= 1.2.0, **PHP 7**)](http://php.net/manual/de/function.json-encode.php) and [`json_decode()` (PHP 5 >= 5.2.0, PECL json >= 1.2.0, **PHP 7**)](http://php.net/manual/de/function.json-decode.php) are supported in PHP7. – Axel Nov 09 '17 at 16:20
  • This worked for me as well. I am using it for Drupal/Apache Solr – AllisonC Jul 25 '18 at 15:27
  • But if you have BINARY data, let's said... an object that contain a binary. Then this snippet will brake the code giving you a null object – Max Cuttins Nov 06 '18 at 11:24
34

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;
}
Alexander Yancharuk
  • 13,817
  • 5
  • 55
  • 55
Sergio
  • 1,139
  • 14
  • 24
  • I can't read the array resulting of an object casting: http://codepad.viper-7.com/AkX5pq Do you have any explanation about that? – Damien Jan 23 '13 at 11:53
  • 1
    I like this answer best. Andy E's recursive function essentially does the same thing, but I find this one easier to understand. – HartleySan Apr 29 '14 at 16:49
20
$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 :)

m3nda
  • 1,986
  • 3
  • 32
  • 45
  • It works perfect only with public object attributes. Doesn't consider private ones. – Limon Jun 19 '14 at 15:44
  • Here are some explanation about use JsonSerialize function, but is not one line solution and i read about is not a good practice :( http://stackoverflow.com/questions/7005860/php-json-encode-class-private-members. Thank you for the advice. – m3nda Jun 19 '14 at 17:30
  • How to convert it back to an object? – Peyman Mohamadpour Jan 20 '17 at 08:41
18

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();
Styx
  • 1,303
  • 1
  • 19
  • 30
2

Try this:-

 <?php
  print_r(json_decode(json_encode($response->response->docs),true));
 ?>
kunal
  • 4,122
  • 12
  • 40
  • 75
2

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

Hemant Parmar
  • 3,924
  • 7
  • 25
  • 49
0

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.

Nhan
  • 3,595
  • 6
  • 30
  • 38
Leon Clements
  • 95
  • 1
  • 7
-1

You can also use array_values() method of php

Rikin Adhyapak
  • 483
  • 5
  • 8
-2
//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);
            }
        }
    }