Skip to content

Instantly share code, notes, and snippets.

@gotohr
Created May 26, 2015 20:05
Show Gist options
  • Save gotohr/fc9d17e8c03675e8539d to your computer and use it in GitHub Desktop.
Save gotohr/fc9d17e8c03675e8539d to your computer and use it in GitHub Desktop.
php dot string to tree
<?php
$map = array(
'person.firstname' => 'John',
'person.lastname' => 'Doe',
'gender' => 'male',
'some.arbitrary.structure.key' => 'smthng'
);
function tree($map) {
$fn = function($carry, $key){
return array($key => $carry);
};
$result = array();
foreach($map as $key => $val) {
$path = array_reverse(explode('.', $key));
$result = array_merge_recursive($result, array_reduce($path, $fn, $val));
}
return $result;
}
$result = tree($map);
echo '<pre>';
print_r($result);
echo '</pre>';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment