Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

get value from array using string php

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...