Skip to content

Instantly share code, notes, and snippets.

@xemoe
Last active August 29, 2015 14:25
Show Gist options
  • Save xemoe/d28380f9b41759445092 to your computer and use it in GitHub Desktop.
Save xemoe/d28380f9b41759445092 to your computer and use it in GitHub Desktop.
PHP Array nested get/set
<?php
function array_bags($keys, $root, $bags)
{
$key = array_shift($keys);
$root = $root[$key];
$bags[] = ['key' => $key, 'root' => $root];
$length = sizeof($keys);
if ($length > 0) {
return array_bags($keys, $root, $bags);
} elseif ($length == 0) {
return $bags;
} else {
return $root;
}
}
function array_nested_get($keys, $root)
{
$key = array_shift($keys);
$root = $root[$key];
$length = sizeof($keys);
if ($length > 0) {
return array_nested_get($keys, $root);
} else {
return $root;
}
}
function array_nested_set($keys, $root, $value)
{
$bags = array_bags($keys, $root, []);
$length = sizeof($bags);
$current = null;
$nextKey = null;
$previousRoot = null;
for ($index = 0; $index < $length; $index++) {
$current = array_pop($bags);
$nextKey = $current['key'];
//
// Modification part
//
if ($index == 0) {
$previousRoot = $value;
}
if (is_array($previousRoot)) {
unset($previousRoot['key']);
unset($previousRoot['root']);
$current[$nextKey] = array_merge($current['root'], $previousRoot);
} else {
$current[$nextKey] = $previousRoot;
}
$previousRoot = $current;
}
unset($current['key']);
unset($current['root']);
$current = array_merge($root, $current);
return $current;
}
$root = ['l1' => ['l2' => ['l3' => 'foo', 'r3' => 2], 'r2' => 1 ], 'r1' => 0];
$expect = ['l1' => ['l2' => ['l3' => 'bar', 'r3' => 2], 'r2' => 1 ], 'r1' => 0];
$key = 'l1.l2.l3';
$keys = explode('.', $key);
$bags = [];
assert('foo' == array_nested_get($keys, $root), 'array_nested_get should return foo');
$new = array_nested_set($keys, $root, 'bar');
assert($expect == $new);
assert('bar' == array_nested_get($keys, $new), 'array_nested_get should return bar');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment