使用字符串 php 从数组中获取值

get value from array using string php

我有以下数组:

array('data' => array('one' => 'first', 'two' => 'second'));

如何使用字符串获取键 'one' 的值:

echo __('data.one');

function __($key) {
    $parts = explode('.', $key);
    $array = array('data' => array('one' => 'first', 'two' => 'second'));
    return ???;
}

谢谢你!

这应该适合你:

return $array["data"]["one"];

另请参阅:http://php.net/manual/en/language.types.array.php
并且:PHP - Accessing Multidimensional Array Values

编辑:

这应该适合你:

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

?>

添加您自己的错误处理,以防键路径不在您的数组中,而是类似于:

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