Last active
August 29, 2015 13:57
-
-
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.
This file contains hidden or 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
<?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