Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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!

question from:https://stackoverflow.com/questions/65924493/access-array-value-using-index-variable-that-contains-brackets

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.3k views
Welcome To Ask or Share your Answers For Others

1 Answer

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...