Skip to content

Instantly share code, notes, and snippets.

@krmgns
Last active August 29, 2015 14:12
Show Gist options
  • Save krmgns/5643ca4f7696001d8472 to your computer and use it in GitHub Desktop.
Save krmgns/5643ca4f7696001d8472 to your computer and use it in GitHub Desktop.
function extract_array_path($path, $value = null, $base = null) {
if ($base === null) {
static $base = array();
}
$exp = explode('.', $path);
$tmp =& $base;
foreach($exp as $i) {
$tmp =& $tmp[$i];
}
// Set value
if ($value !== null) {
$tmp = $value;
}
unset($tmp);
return $base;
}
function extract_object_path($path, $value = null, $base = null) {
if ($base === null) {
static $base = array();
$base = (object) $base;
}
$exp = explode('.', $path);
$tmp =& $base;
foreach($exp as $i) {
$tmp =& $tmp->{$i};
}
// Set value
if ($value !== null) {
$tmp = $value;
}
unset($tmp);
return $base;
}
function get_array_value($base, $path, $defval = null) {
$eval = '$base[\''. str_replace('.', '\'][\'', $path) .'\']';
eval('$return = '. $eval .';');
return ($return !== null) ? $return : $defval;
}
function get_object_value($base, $path, $defval = null) {
$eval = '$base->'. str_replace('.', '->', $path);
eval('$return = '. $eval .';');
return ($return !== null) ? $return : $defval;
}
function get_value($base, $path, $defval = null) {
if (is_array($base)) return get_array_value($base, $path, $defval);
if (is_object($base)) return get_object_value($base, $path, $defval);
}
// Set
$base = extract_array_path('lorem.ipsum.dolor0');
$base = extract_array_path('lorem.ipsum.dolor1', 1, $base);
pre($base);
// Get
$dolor0 = get_value($base, 'lorem.ipsum.dolor0');
$dolor1 = get_value($base, 'lorem.ipsum.dolor1');
prd($dolor0);
prd($dolor1);
// Set
$base = extract_object_path('lorem.ipsum.dolor0');
$base = extract_object_path('lorem.ipsum.dolor1', 1, $base);
pre($base);
// Get
$dolor0 = get_value($base, 'lorem.ipsum.dolor0');
$dolor1 = get_value($base, 'lorem.ipsum.dolor1');
prd($dolor0);
prd($dolor1);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment