来自PHP中变量的数组路径 [英] Array path from variable in PHP

查看:120
本文介绍了来自PHP中变量的数组路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我写了一个类,可以解析XML文档并从中创建SQL查询,以根据设置更新或插入新行.

So I wrote a class that can parse XML documents and create SQL queries from it to update or insert new rows depending on the settings.

由于脚本必须处理任意数量的嵌套块,因此我要放置所有值的数组具有动态创建的路径,类似于以下示例:

Because the script has to work with any amount of nested blocks, the array that I'm putting all the values in has its path dynamically created much like the following example:

$path = array('field1','field2');
$path = "['".implode("']['",$path)."']";

eval("\$array".$path."['value'] = 'test';");

基本上$path包含一个数组,该数组显示我们当前在数组中的深度,如果$path包含例如值main_tablefield,我想将$array['main_table']['field']['value']设置为'test'

Basically $path contains an array that shows how deep in the array we currently are, if $path contains for instance the values main_table and field I want set $array['main_table']['field']['value'] to 'test'

如您所见,我当前正在使用eval进行此操作,并且工作正常.我只是想知道是否有一种方法可以不使用eval.

As you can see I am currently using eval to do this, and this works fine. I am just wondering if there is a way to do this without using eval.

类似的东西 $array{$path}['value'] = 'test';,但实际上有一些作用.

Something like $array{$path}['value'] = 'test'; but then something that actually works.

有什么建议吗?

编辑

我正在寻找替代方法的原因是因为我认为eval是一种不好的做法.

The reason I'm looking for an alternative is because I think eval is bad practice.

第二编辑

将实际代码更改为虚拟代码,因为这会引起很多误会.

Changed actual code to dummy code because it was causing a lot of misunderstandings.

推荐答案

使用类似这样的内容:

/**
 * Sets an element of a multidimensional array from an array containing
 * the keys for each dimension.
 * 
 * @param array &$array The array to manipulate
 * @param array $path An array containing keys for each dimension
 * @param mixed $value The value that is assigned to the element
 */
function set_recursive(&$array, $path, $value)
{
  $key = array_shift($path);
  if (empty($path)) {
    $array[$key] = $value;
  } else {
    if (!isset($array[$key]) || !is_array($array[$key])) {
      $array[$key] = array();
    }
    set_recursive($array[$key], $path, $value);
  }
}

这篇关于来自PHP中变量的数组路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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