如何通过路径访问多维数组元素?

编程入门 行业动态 更新时间:2024-10-10 04:24:07
本文介绍了如何通过路径访问多维数组元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

可能重复: 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.

更多推荐

如何通过路径访问多维数组元素?

本文发布于:2023-11-28 18:11:04,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1643433.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多维   数组   路径   元素

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!