如何通过路径访问多维数组元素? [重复]

问题描述 投票:0回答:3

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

我有一个像这样的数组:

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

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

例如,以下函数应返回

$path = 'image/colors/blue';

12345


php arrays multidimensional-array
3个回答
2
投票

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

您当然应该添加错误检查等。


1
投票

$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



0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.