php - Call array with array_key and get the array value -
i want send key of multi dimension array function , value of key, should item or , sub array. imagine have function:
public function returnarray($index){ $arr = [ 'name' => 'ali', 'children' => [ '1' => 'reza', '2' => 'hasan', '3' => 'farhad', 'info' => [ 'a', 'b', 'c' ] ] ]; return $arr[$index]; }
and when call this:
returnarray('[name][children][info]')
the result should info
array.
what should do?
thanks in advance.
just fyi, code smells bad - re-implementing array within string, makes me think it's idea access array directly this:
$arr["name"]["children"]["info"]
but, sake of complete answers, let's write function want.
firstly, rather passing in index within single string, functions have parameters already, let's exploit feature. within function, can array containing passed-in parameters using [func_get_args](http://php.net/manual/en/function.func-get-args.php)
.
// remove parameter $index, don't know how many parameters there be. function returnarray(){ $arr = [ 'name' => 'ali', 'children' => [ '1' => 'reza', '2' => 'hasan', '3' => 'farhad', 'info' => [ 'a', 'b', 'c' ] ] ]; // store reference position in array care about: $position = $arr; foreach(func_get_args() $arg) { // update reference position according passed in parameters. $position = $position[$arg]; } return $position; }
then can call function this:
returnarray("children", "info"); /* returns: array(3) { [0]=> string(1) "a" [1]=> string(1) "b" [2]=> string(1) "c" } */
Comments
Post a Comment