Created
November 23, 2016 12:17
-
-
Save devgnx/cdad7723d137f71dcb0978058b8f46c1 to your computer and use it in GitHub Desktop.
Convert arrays to object, preserving arrays with numeric keys
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function convertToObject($array) | |
{ | |
reset($array); | |
if ($isNumericKey = is_numeric(key($array))) { | |
$object = []; | |
} else { | |
$object = new \stdClass(); | |
} | |
foreach ($array as $key => $value) { | |
if (is_array($value)) { | |
$value = convertToObject($value); | |
} | |
if ($isNumericKey) { | |
$object[$key] = $value; | |
} else { | |
$object->{$key} = $value; | |
} | |
} | |
return $object; | |
} | |
$resultOne = convertToObject(["test" => "to", "pass" => "values", "on" => "object"]); | |
$resultTwo = convertToObject(["test", "to", "dont", "pass", "values", ["on" => ["object"=> "test level 2", "test" => ["level" => "3"]]]]); | |
echo "<pre>"; | |
var_dump($resultOne); | |
echo "</pre>"; | |
echo "<pre>"; | |
var_dump($resultTwo); | |
echo "</pre>"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment