Skip to content

Instantly share code, notes, and snippets.

@aaronpeterson
Last active August 29, 2015 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aaronpeterson/9882497 to your computer and use it in GitHub Desktop.
Save aaronpeterson/9882497 to your computer and use it in GitHub Desktop.
Read dot or php style input notation in any object at any depth.
<?php
$data = array(
'namespace' => array(
'foo' => array(
'bar' => 'You found me!'
)
)
);
$vs = new ValueStore;
d( $vs->deepValue('namespace.foo.bar', $data) );
d( $vs->deepValue('namespace[foo][bar]', $data) );
d( $vs->deepValue('nope', $data) );
d( $vs->deepValue('namespace', $data) );
d( $vs->deepValue('namespace.foo', $data) );
class ValueStore {
public function deepValue($name, $data) {
$data = (array) $data;
$nameParts = $this->getNameParts($name);
foreach ($nameParts as $part) {
$data = empty($data[$part]) ? null : $data[$part];
if (!$data)
break;
}
return $data;
}
public function getNameParts($name) {
if (strpos($name, '[') !== false) {
// php style
preg_match_all("/([^\[\]]+)/i", $name, $matches, PREG_PATTERN_ORDER);
} elseif (strpos($name, '.') !== false) {
// dot notation
preg_match_all("/([^\.]+)/i", $name, $matches, PREG_PATTERN_ORDER);
} else {
$matches[] = array($name);
}
return $matches[0];
}
}
function d($d) { ?><pre><?php var_dump($d); ?></pre><?php }
/*
So boss.
string(13) "You found me!"
string(13) "You found me!"
NULL
array(1) {
["foo"]=>
array(1) {
["bar"]=>
string(13) "You found me!"
}
}
array(1) {
["bar"]=>
string(13) "You found me!"
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment