Last active
March 3, 2022 17:26
-
-
Save Gerst20051/b14c05b72c73b49bc2d306e7c8b86223 to your computer and use it in GitHub Desktop.
PHP Unflatten Dot Notation Array
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
<? | |
$results = [ | |
'id' => 'abc123', | |
'address.id' => 'def456', | |
'address.coordinates.lat' => '12.345', | |
'address.coordinates.lng' => '67.89', | |
'address.coordinates.geo.accurate' => true, | |
]; | |
function unflatten($data) { | |
$output = []; | |
foreach ($data as $key => $value) { | |
$parts = explode('.', $key); | |
$nested = &$output; | |
while (count($parts) > 1) { | |
$nested = &$nested[array_shift($parts)]; | |
if (!is_array($nested)) $nested = []; | |
} | |
$nested[array_shift($parts)] = $value; | |
} | |
return $output; | |
} | |
echo json_encode(unflatten($results)); | |
/* | |
{ | |
"id": "abc123", | |
"address": { | |
"id": "def456", | |
"coordinates": { | |
"lat": "12.345", | |
"lng": "67.89", | |
"geo": { | |
"accurate": true | |
} | |
} | |
} | |
} | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I took the liberty of building on this and expanding it to a function that can handle duplication of values when joined data is pulled from a database:
Produces
Sandbox: https://3v4l.org/P4RVZ