阵列:使用点符号设定值? [英] Array: set value using dot notation?

查看:148
本文介绍了阵列:使用点符号设定值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

展望Koh​​ana的文档,我发现这真的有用的功能的,他们使用用点号从一个多维数组中获取值,例如:

  $富=阵列('酒吧'=>阵列('颜色'=>'绿色','大小'=>'M'));
$值=路径($ foo的,'bar.color',NULL,'。');
// $值现在是绿色

我想知道是否有一种方法来设置以同样的方式在一个数组值:

  SET_VALUE($ foo的,'bar.color','黑');

我发现这样做是重楼的数组符号($数组['酒吧'] ['颜色']),然后使用所设置的值。唯一的办法评估

任何想法,以避免EVAL?


解决方案

 函数set_val(阵列和放大器; $改编,$路径,$ VAL)
{
   $ LOC =安培; $编曲;
   的foreach(爆炸('。',$ PATH)为$步)
   {
     $ LOC =安培; $ LOC [$一步];
   }
   返回$ LOC = $ VAL;
}

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

The only way i found to do that is re-building the array notation ($array['bar']['color']) and then set the value.. using 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆