可能的重复:
PHP:使用字符串作为数组索引路径来检索值 https://stackoverflow.com/questions/1677099/php-use-a-string-as-an-array-index-path-to-retreive-a-value
我有一个像这样的数组:
$array['image']['comment'] = 'something';
$array['image']['tag'] = 'happy';
$array['image']['colors']['blue'] = '12345';
如果我有字符串中每个元素的路径,如何设置或获取数组值?
例如哪里$path = 'image/colors/blue';
下面的函数应该返回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
您当然应该添加错误检查等。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)