get value from array using string php

2019-09-07 22:36发布

问题:

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!

回答1:

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


回答2:

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;

?>


标签: php arrays key