Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 使用类似路径的字符串访问多维数组_Php_Arrays_Multidimensional Array - Fatal编程技术网

Php 使用类似路径的字符串访问多维数组

Php 使用类似路径的字符串访问多维数组,php,arrays,multidimensional-array,Php,Arrays,Multidimensional Array,我有一个名为get\u config()的函数和一个名为$config的数组 我使用get\u config('site.name')调用该函数,并且正在寻找返回$config值的方法,因此对于本例,该函数应该返回$config['site']['name'] 我几乎要发疯了-尽量不使用eval()!有什么想法吗 编辑:到目前为止,我有: function get_config($item) { global $config; $item_config = ''; $item_pa

我有一个名为
get\u config()
的函数和一个名为
$config
的数组

我使用
get\u config('site.name')
调用该函数,并且正在寻找返回
$config
值的方法,因此对于本例,该函数应该返回
$config['site']['name']

我几乎要发疯了-尽量不使用
eval()
!有什么想法吗

编辑:到目前为止,我有:

function get_config($item)
{
  global $config;

  $item_config = '';
  $item_path = ''; 

  foreach(explode('.', $item) as $item_part)
  {
    $item_path .= $item."][";

    $item = $config.{rtrim($item_path, "][")};
  }

  return $item;
}
这应该起作用:

function get_config($config, $string) {
    $keys = explode('.', $string);
    $current = $config;
    foreach($keys as $key) {
        if(!is_array($current) || !array_key_exists($key, $current)) {
            throw new Exception('index ' . $string . ' was not found');
        }
        $current = $current[$key];
    }
    return $current;
}

你可以试试像

function get_config($item)
{
      global $config;
      return $config[{str_replace('.','][',$item)}];
}

在get_config函数中,可以使用php中的explode函数解析字符串

function get_config($data){
 $pieces = explode(".", $data);

 return $config[$pieces[0]][$pieces[1]];

}

让我们看看你到底有什么?不太好。然后我需要使用拆分字符串来访问多维数组-这似乎是
explode()
无法做到的。是的!它起作用了。非常感谢。我会尽快接受你的答复