Last active
July 5, 2019 08:17
-
-
Save crtl/62de35d8c891bf218affa9b8212a9361 to your computer and use it in GitHub Desktop.
Function to access associative arrays by string paths
This file contains 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
/** | |
* @param string $path The path of keys to access | |
* @param array $array The array to read from | |
* @param string $seperator The seperator to split the string by | |
* @return array|mixed|null The requested value or null | |
*/ | |
function array_path(string $path, array $array, string $seperator = ".") { | |
$parts = explode($seperator, $path); | |
$current = $array; | |
foreach ($parts as $part) { | |
if (!isset($current[$part])) { | |
return null; | |
} | |
$current = $current[$part]; | |
} | |
return $current; | |
} | |
$data = [ | |
"customers" => [ | |
[ | |
"name" => "Jhon Doe", | |
"age" => 31, | |
] | |
], | |
"nested" => [ | |
"foo" => "bar" | |
] | |
]; | |
var_dump(array_path("customers.0", $data)); //array["name" => ..., "age" => ...] | |
var_dump(array_path("nested.foo", $data)); //string "bar" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment