I have the following array:
array('data' => array('one' => 'first', 'two' => 'second'));
How i can get the value of key 'one' using string:
echo __('data.one');
function __($key) {
$parts = explode('.', $key);
$array = array('data' => array('one' => 'first', 'two' => 'second'));
return ???;
}
Thank u!
Add your own error handling in case the key path isn't in your array, but something like:
$array = array('data' => array('one' => 'first', 'two' => 'second'));
$key = 'data.one';
function find($key, $array) {
$parts = explode('.', $key);
foreach ($parts as $part) {
$array = $array[$part];
}
return $array;
}
$result = find($key, $array);
var_dump($result);
This should work for you:
return $array["data"]["one"];
Also for more information and to learn a little bit see: http://php.net/manual/en/language.types.array.php
And : PHP - Accessing Multidimensional Array Values
EDIT:
This should work for you:
<?php
$str = "data.one";
$keys = explode(".", $str);
$array = array('data' => array('one' => 'first', 'two' => 'second'));
$access = $array;
foreach($keys as $v)
$access = $access[$v];
echo $access;
?>