PHP: Recursively convert an object to an array

By , June 16, 2010 1:00 pm

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.

  1.  
  2. function object_to_array($obj) {
  3. if(is_object($obj)) $obj = (array) $obj;
  4. if(is_array($obj)) {
  5. $new = array();
  6. foreach($obj as $key => $val) {
  7. $new[$key] = object_to_array($val);
  8. }
  9. }
  10. else $new = $obj;
  11. return $new;
  12. }
  13.  

Leave a Reply

6 Responses to“ PHP: Recursively convert an object to an array”

  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. Miklos Szabo says:

    Just what I needed. Thanks.

  3. Jose Onate says:

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

  4. Arthur says:

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

Theme by Blam Designs
Based on Themocracy

Add this ribbon to your WordPress website re-abolish slavery
%d bloggers like this: