php - Use array of keys to access multidimensional array? -
for example, if had array:
$my_array = array('a' => array('b' => 'c'));
is there way access this:
$my_value = access_array($my_array, array('a', 'b')); // $my_value == 'c'
i know write this, i'm curious if exists in php already.
easy
function get_nested_key_val($ary, $keys) { foreach($keys $key) $ary = $ary[$key]; return $ary; } $my_array = array('a' => array('b' => 'c')); print get_nested_key_val($my_array, array('a', 'b'));
for functional programming proponents
function get_nested_key_val($ary, $keys) { return array_reduce($keys, function($a, $k) { return $a[$k]; }, $ary); }
Comments
Post a Comment