开发者

Assign to an arbitrarily deep array index?

If I have an array which c开发者_如何学JAVAorresponds to successively recursive keys in another array, what is the best way to to assign a value to that "path" (if you want to call it that)?

For example:

$some_array = array();
$path = array('a','b','c');
set_value($some_array,$path,'some value');

Now, $some_array should equal

array(
  'a' => array(
    'b' => array(
      'c' => 'some value'
)))

At the moment, I am using the following:

function set_value(&$dest,$path,$value) {
  $addr = "\$dest['" . implode("']['", $path) . "']";
  eval("$addr = \$value;");
}

Obviously, this is a very naive approach and poses a security risk, so how would you do it?


Recursive solution (not tested):

 function set_value(&$dest,$path,$value) {
      $index=array_shift($path);
      if(empty($path)){
        // on last level
        $dest[$index]=$value;
      }
      else{
        // descending to next level
        set_value($dest[$index],$path,$value);
      }
    }


Wow, reminds me of Lisp.

Yea, eval is generally not the best idea.

Personally, I would simply iterate:

function set_value(&$dest,$path,$value) {
  $val =& $dest;
  for($i = 0; $i > count($path) - 1; $i++) {
     $val =& $val[$i];
  }

  $val[$path[$i]] = $value;
}

If you're in PHP 5 you can probably get rd of some of those '&' too


function set_value(&$dest, $path, $value) {
    $dest = array(array_pop($path) => $value);
    for($i = count($path) - 1; $i >= 0; $i--) {
        $dest = array($path[$i] => $dest);
    }
}


function set_value(&$dest, $path, $value)
{
  # allow for string paths of a/b/c
  if (!is_array($path)) $path = explode('/', $path);

  $a = &$dest;
  foreach ($path as $p)
  {
    if (!is_array($a)) $a = array();
    $a = &$a[$p];
  }

  return $a = $value;
}


set_value($a, 'a/b/c', 'foo');

Updated to work with keys that don't yet exist, and to accept either an array or a string path.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜