如何通过路径访问多维数组元素? [英] How can I access a multidimensional array element by path?

查看:90
本文介绍了如何通过路径访问多维数组元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
PHP:使用字符串作为检索值的数组索引路径

我有一个像这样的数组:

I have an array like so:

$array['image']['comment'] = 'something';
$array['image']['tag'] = 'happy';
$array['image']['colors']['blue'] = '12345';

如果我有字符串中每个元素的路径,如何设置或获取数组值?

If I have the path to each element in a string, how can I set or get the array value?

例如,其中 $ path ='image/colors/blue'; 以下函数应返回 12345

e.g where $path = 'image/colors/blue'; the below function should return 12345

function get_array($array, $path)
{
//what goes here?
}

function set_array($array, $path, $value)
{
//what goes here?
}

推荐答案

尝试一下:

$arr = array('a' => 'A', 'b' => array('c' => 'C', 'd' => array('e'=>'E')));

function read_array($array, $path)
{
  if($pos = strpos($path, '/') !== false){
    $key = substr($path, 0, $pos);
    $restOfKey = substr($path, $pos + 1); 
    return read_array($array[$key], $restOfKey);
  } else {
    $key = $path;
    return $array[$key];
  }
}

echo read_array($arr, 'a');      //A
echo read_array($arr, 'b/c');    //C
echo read_array($arr, 'b/d/e');  //E

您当然应该添加错误检查和所有内容.

You should of course add error checking and all.

这篇关于如何通过路径访问多维数组元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆