Array path from variable in PHP

后端 未结 3 1120
时光说笑
时光说笑 2021-01-27 12:51

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 wit

相关标签:
3条回答
  • 2021-01-27 13:12

    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.

    0 讨论(0)
  • 2021-01-27 13:13

    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);
      }
    }
    
    0 讨论(0)
  • 2021-01-27 13:20

    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);
    
    0 讨论(0)
提交回复
热议问题