php - 在数组中设置嵌套项

标签 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”的方法?

最佳答案

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

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;
}

关于php - 在数组中设置嵌套项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14793782/

相关文章:

php - Magento 2 产品集合显示查询

java - 为什么Java中以下列表无法转换为字符串数组

c - 数组中的字符串到另一个数组中

arrays - MongoDB:删除除最后 X 个条目之外的所有数组条目

javascript eval 和对象评估

php - 格式化查询输出 : using sql or php functions?

php - 我需要计算计数项目的百分比

php - 使用PDO显示当前用户名

lisp - 在 common-lisp 中,我如何覆盖/更改特定类型对象的评估行为?

javascript - 我想加载 JSON 时可以使用原始 JavaScript 吗?