栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何通过键名/路径访问和操作多维数组?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何通过键名/路径访问和操作多维数组?

假设

$path
通过
explode
(或添加到函数)已经是一个数组,则可以使用引用。您需要添加一些错误检查以防无效
$path
等(请考虑
isset
):

$key = 'b.x.z';$path = explode('.', $key);

吸气剂

function get($path, $array) {    //$path = explode('.', $path); //if needed    $temp =& $array;    foreach($path as $key) {        $temp =& $temp[$key];    }    return $temp;}$value = get($path, $arr); //returns NULL if the path doesn't exist

二传手/创造者

如果您传递的数组尚未定义,则此组合将在现有数组中设置一个值或创建该数组。确保定义

$array
要通过引用传递
&$array

function set($path, &$array=array(), $value=null) {    //$path = explode('.', $path); //if needed    $temp =& $array;    foreach($path as $key) {        $temp =& $temp[$key];    }    $temp = $value;}set($path, $arr);//orset($path, $arr, 'some value');

取消设定

这将

unset
是路径中的最终键:

function unsetter($path, &$array) {    //$path = explode('.', $path); //if needed    $temp =& $array;    foreach($path as $key) {        if(!is_array($temp[$key])) { unset($temp[$key]);        } else { $temp =& $temp[$key];        }    }}unsetter($path, $arr);

*原始答案的功能有限,以防某些人使用它们:

塞特犬

确保定义

$array
要通过引用传递
&$array

function set(&$array, $path, $value) {    //$path = explode('.', $path); //if needed    $temp =& $array;    foreach($path as $key) {        $temp =& $temp[$key];    }    $temp = $value;}set($arr, $path, 'some value');

或者,如果您想返回更新的数组(因为感到无聊):

function set($array, $path, $value) {    //$path = explode('.', $path); //if needed    $temp =& $array;    foreach($path as $key) {        $temp =& $temp[$key];    }    $temp = $value;    return $array;}$arr = set($arr, $path, 'some value');

创作者

如果您不想创建数组并选择设置值:

function create($path, $value=null) {    //$path = explode('.', $path); //if needed    foreach(array_reverse($path) as $key) {        $value = array($key => $value);    }    return $value;}$arr = create($path);    //or$arr = create($path, 'some value');

为了娱乐

构造和计算类似于

$array['b']['x']['z']
给定字符串的内容
b.x.z

function get($array, $path) {    //$path = explode('.', $path); //if needed    $path = "['" . implode("']['", $path) . "']";    eval("$result = $array{$path};");    return $result;}

设置类似

$array['b']['x']['z'] = 'some value';

function set(&$array, $path, $value) {    //$path = explode('.', $path); //if needed    $path = "['" . implode("']['", $path) . "']";    eval("$array{$path} = $value;");}

取消类似的设置

$array['b']['x']['z']

function unsetter(&$array, $path) {    //$path = explode('.', $path); //if needed    $path = "['" . implode("']['", $path) . "']";    eval("unset($array{$path});");}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/433143.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号