数组:使用点表示法设置值? [英] Array: set value using dot notation?
本文介绍了数组:使用点表示法设置值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
查看 Kohana 文档,我发现他们使用了这个非常有用的功能使用点表示法从多维数组中获取值,例如:
Looking into Kohana documentation, i found this really usefull function that they use to get values from a multidimensional array using a dot notation, for example:
$foo = array('bar' => array('color' => 'green', 'size' => 'M'));
$value = path($foo, 'bar.color', NULL , '.');
// $value now is 'green'
我想知道是否有一种方法可以以相同的方式设置数组值:
Im wondering if there is a way to set the an array value in the same way:
set_value($foo, 'bar.color', 'black');
我发现这样做的唯一方法是重新构建数组符号 ($array['bar']['color']),然后使用 eval
设置值..
The only way i found to do that is re-building the array notation ($array['bar']['color']) and then set the value.. using eval
.
有什么办法可以避免 eval 吗?
Any idea to avoid eval?
推荐答案
function set_val(array &$arr, $path,$val)
{
$loc = &$arr;
foreach(explode('.', $path) as $step)
{
$loc = &$loc[$step];
}
return $loc = $val;
}
这篇关于数组:使用点表示法设置值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文