Skip to content

Instantly share code, notes, and snippets.

@blynx
Last active January 26, 2017 02:42
Show Gist options
  • Save blynx/20cf9ccae4b551d4fd6325395ec6ff02 to your computer and use it in GitHub Desktop.
Save blynx/20cf9ccae4b551d4fd6325395ec6ff02 to your computer and use it in GitHub Desktop.
PHP function: Get values by given path in plain or mix-nested objects and arrays
<?php
/**
* value_in
*
* @param mixed $haystack array or object or nested mix of both
* @param string $path path in any token-separated notation
* @param string $token path separator token
* @return mixed resolved value
*/
function value_in($haystack, $path, $token = ".") {
$path = trim($path, $token); // path.to.place
$segments = explode($token, $path); // ["path", "to", "place"]
$remains = $haystack;
foreach ($segments as $segment) {
if (gettype($remains) === 'array' && isset($remains[$segment])) {
$remains = $remains[$segment];
} else if (gettype($remains) === 'object' && isset($remains->$segment)) {
$remains = $remains->$segment;
} else {
return null;
}
}
return $remains;
}
/**
* test
*
*/
// array probe
$array = [
"city" => [
"quartier" => [
"street" => "mark",
"road" => "siri"
]
],
"town" => [
"area" => [
"street" => "parents",
"place" => "mayor"
]
]
];
// mixed probe
$mixed = new stdClass();
$garden = [
"tree" => [
"crown",
"leaves"
],
"flowers",
"lawn" => (object) [
"blade of grass #1",
"blade of grass #2",
"blade of grass #3",
"theVeryCenter" => "blade of grass #4",
"blade of grass #5"
]
];
$mixed->garden = (object) $garden;
$mixed->colony = $array;
// testing array
echo "\n";
echo "\n" . value_in($array, "city.quartier.street"); // ⮑ "mark"
echo "\n" . value_in($array, "town.area."); // ⮑ "mark"
echo "\n" . value_in($array, "/town/area/street", "/"); // // ⮑ "parents"
echo "\n";
// testing mixed structure
echo "\n";
echo "\n" . value_in($mixed, "garden.tree.0"); // ⮑ "crown"
echo "\n" . value_in($mixed, "garden.lawn.2"); // ⮑ "blade of grass #3"
echo "\n" . value_in($mixed, "garden.lawn")->theVeryCenter; // ⮑ "blade of grass #4"
echo "\n" . gettype(value_in($mixed, "garden.bush")); // ⮑ NULL
echo "\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment