Ben Lobaugh Online

/(bb|[^b]{2})/

PHP: Recursively convert an object to an array

When pulling in array from outside data sources you often receive an array back. The problem is that sometimes even though you know you should have an array your application does not and therefore assigns it to the stdObject object, which of course is nothing. To make it usable you must convert it back into an array. With a simple object that may be as simple as a cast, but when you are working with large complex datasets that may be several layers deep you need to make sure you get at all of them. Enter beautiful recursion. After playing with PHPs array_walk_recursive() for a bit I hit on a custom recursive function that does exactly the job. Simply pass it your object and it will munch away at it trying to convert it into a PHP array. Take a gander at the code for this below.

function object_to_array($obj) {
    if(is_object($obj)) $obj = (array) $obj;
    if(is_array($obj)) {
        $new = array();
        foreach($obj as $key => $val) {
            $new[$key] = object_to_array($val);
        }
    }
    else $new = $obj;
    return $new;       
}

Previous

PHP: Show error on screen when disabled by php.ini

Next

jQuery: Selecting only the first level children

13 Comments

  1. Thank you for this wonderful post. This was exactly what I was looking for. Gets the job done perfectly. Thanks again for this great PHP contribution.

  2. Thank you, good sir.

  3. Miklos Szabo

    Just what I needed. Thanks.

  4. This is the right script, with one addition:
    For a complex object, I was getting null chars within the array keys stemming from the simplification of the object when type-casted as (array).

    When var_dumped, a (str) array key would look like this:
    ‘arrayKey’ (str 9 chars, with the null char hidden within)
    the actual string: array(NULLCHAR)Key

    The best way to deal with it is to further clean the keys by removing null chars (char 0). This adaptation works:

    function objectToArray($obj) {
    if(is_object($obj)) {
    $obj = (array) $obj;
    $aobj = array();
    foreach ($obj as $key=>$value) {
    $aobj[_cleanStr($key)] = $value; //sanitize the str for null chars
    }
    $obj = $aobj;
    }
    if(is_array($obj)) {
    $new = array();
    foreach($obj as $key => $val) {
    $new[_cleanStr($key)] = objectToArray($val);
    }
    }
    else $new = $obj;
    return $new;
    }

    function _cleanStr($str) {
    $str = str_replace(“”, “”, $str); //remove null chars
    return $str;
    }

  5. You can achieve the same result in 1 line!
    $result = json_decode(json_encode($obj), true);

    • rtmvnv

      Using json brings not the same result. You’ll lose protected and private properties of the object.

  6. angelo

    Very good function.

  7. UncaAlby

    It’s a good function. My only comment is that empty data, which I’d like to show as an empty string, will instead show as a zero-length array.

    E.g.:
    Array {
    [last_name] = ‘Smith’,
    [first_name] = ‘John’,
    [middle_initial] = array {
    }
    }
    But it’s not a big deal, I generally know the keys that I want, where they are and what kind of results they should have, so a simple test converts it back from empty array to the desired empty string.

  8. Mayowa

    Awesome code. Just what i needed.

  9. Nice, Thanks for sharing!

  10. Very nice and powerful function. I have battled this for 4 days with functions from various websites across the internet and I haven’t found the perfect solution until I found this function. Thank you very much for this wonderful php function.

    Most of the solutions I found were only meant for single objects, but once I started using them on nested objects they failed to work. Now your solution allowed me to convert a very complex PHP object to an associative array and now I can call this function anytime and have it convert any object into a multidimensional array, this allows me to use the in_array() function as I want to.

    Thank you once again 🙂

  11. I forgot to ask, do you know if there is a much simpler way to find out if an item is within a given nested object without converting the object to an array? In an array you will use `in_array()` function like “if ( in_array($item, $object) )”, is the a way to do it like this with objects without converting to array?

Leave a Reply

Powered by WordPress & Drip City Coffee