Array path from variable in PHP

后端 未结 3 1122
时光说笑
时光说笑 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: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);
      }
    }
    

提交回复
热议问题