Last Updated: June 11, 2021
·
13.81K
· joakley77

PHP - Convert mixed array & objects recursively

Ever gotten back mixed data that contained arrays and objects? This snippet of code will recursively convert that data to a single type (array or object) without the nested foreach loops. Hope it helps someone!

Example

<?php
abstract class Util {
    public static function object_to_array($d) {
        if (is_object($d))
            $d = get_object_vars($d);

        return is_array($d) ? array_map(__METHOD__, $d) : $d;
    }

    public static function array_to_object($d) {
        return is_array($d) ? (object) array_map(__METHOD__, $d) : $d;
    }
}
?>

Procedural way

<?php
function object_to_array($d) {
    if (is_object($d))
        $d = get_object_vars($d);

    return is_array($d) ? array_map(__FUNCTION__, $d) : $d;
}

function array_to_object($d) {
    return is_array($d) ? (object) array_map(__FUNCTION__, $d) : $d;
}
?>

6 Responses
Add your response

or you could just do...

$array = (array) $object;

$object = (object) $array;

over 1 year ago ·

Whoops. I should have probably included that this applies to mixed multidimensional arrays and objects. Type casting would only work at the top level and not apply to the children.

** I edited the tip to reflect that I originally intended.

over 1 year ago ·

Yes, you can type cast a single object or array. The point here is to do it recursively over a large array/object set.

Personally, I prefer to work with objects so this comes in handy to convert a multidimensional array into a series of parent/child objects. I have also run across instances of receiving large object sets where it makes more sense to work with arrays. That's where this comes in handy.

over 1 year ago ·

I really like the recursive logic using magic constants! Bonus points for not using a loop - array_map :)

over 1 year ago ·

Hi,

another subtle alternative : https://gist.github.com/victorbstan/744478

over 1 year ago ·

just what I needed top work

over 1 year ago ·