可能重复:
PHP:使用字符串作为数组索引路径来检索值
我有一个像这样的数组:
$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
$array['image']['comment'] = 'something';
$array['image']['tag'] = 'happy';
$array['image']['colors']['blue'] = '12345';
function get_array($array, $path) {
if(strpos('/', $path) > 0) {
list($first, $second, $third) = explode('/', $path);
return $array[$first][$second][$third];
}
}
get_array($array, 'image/colours/blue');