Skip to content

Instantly share code, notes, and snippets.

@devgnx
Created November 23, 2016 12:17
Show Gist options
  • Save devgnx/cdad7723d137f71dcb0978058b8f46c1 to your computer and use it in GitHub Desktop.
Save devgnx/cdad7723d137f71dcb0978058b8f46c1 to your computer and use it in GitHub Desktop.
Convert arrays to object, preserving arrays with numeric keys
<?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