在数组中设置嵌套项

时间:2013-02-10 01:43:31

标签: php arrays eval

我的职能:

function setItem(array $arr, $item, $value, $delimiter = '.') {
    $nodes = explode($delimiter, $item);
    $code = "\$arr['".join("']['", $nodes)."'] = \$value;";
    eval($code);
    return $arr;
}

使用:

$data = array();
$data = setItem($data, 'test.qwerty.sub', 'value');

没有“eval”吗?

2 个答案:

答案 0 :(得分:3)

是的,但它涉及使用引用:

function setItem(array &$arr, $path, $value, $delim = '.'){

  $path = explode($delim, $path);

  $root = &$arr;

  // pointer to the current item      
  $current = &$arr;

  foreach($path as $item){
    $current[$item] = array();

    // set pointer to the newly created array
    $current = &$current[$item];
  }

  // reached the last path component;
  // assign the value to it
  $current = $value;

  return $root;
}

答案 1 :(得分:2)

你可以通过递归来实现:

function setItem($item, $value, $delimiter = '.') {
    $nodes = explode($delimiter, $item, 2);
    if(!isset($nodes[1]))
        $data = $value;
    else
        $data = setItem($nodes[1], $value, $delimiter);
    return array($nodes[0] => $data);
}

$data = setItem('test.qwerty.sub', 'value');