Convert Array to Object/Object to Array Recursively

<?php // Convert array to object or object to array recursively, // with safe mode option for the `array_to_object` function // to exclude conversion on arrays with numeric keys. // // Result for un-safe `array_to_object` mode: // `{"a":"b","c":{"0":"d","1":"e","2":"f"}}` // // Result for safe `array_to_object` mode: // `{"a":"b","c":["d","e","f"]}` // Convert object to array function object_to_array($o) { if (is_array($o) || is_object($o)) { $o = (array) $o; foreach ($o as &$oo) { $oo = object_to_array($oo); } unset($oo); } return $o; } // Convert array to object function array_to_object($a, $safe = true) { if (is_array($a) || is_object($a)) { $a = (array) $a; $a = $safe && count($a) && array_keys($a) !== range(0, count($a) - 1) ? (object) $a : $a; foreach ($a as &$aa) { $aa = array_to_object($aa, $safe); } unset($aa); } return $a; }

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.