Array path from variable in PHP

元气小坏坏 提交于 2020-02-16 08:22:11

问题


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

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'

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.

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

Any suggestions?

EDIT

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

SECOND EDIT

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


回答1:


Use something like this:

/**
 * 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);
  }
}



回答2:


You can bypass the whole counter business with the array append operator:

$some_array[] = 1; // pushes '1' onto the end of the array

As for the whole path business, I'm assuming that's basically an oddball representation of an xpath-like route through your xml document... any reason you can't simply use that string as an array key itself?

$this->BLOCKS['/path/to/the/node/you're/working/on][] = array('name' => $name, 'target' => $target);



回答3:


You can use a foreach with variable variables.

// assuming a base called $array, and the path as in your example:
$path = array('field1','field2');

$$path = $array;
foreach ($path as $v) $$path = $$path[$v];
$$path['value'] = 'test';

Short, simple, and much better than eval.



来源:https://stackoverflow.com/questions/5820879/array-path-from-variable-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!