从字符串创建数组后,向多维数组添加值


add value to multidimensional array after creating an array from a string

好吧,这可能会让人感到困惑。我正在尝试为自己制作一个配置类,我希望它的用法如下:

$this->config->add('world', 'hello');
// This will create array('hello' => 'world')

现在我的问题是,如果我想把我的值添加到一个不存在的多维数组中,但想用这样的东西来创建它:

$this->config->add('my value', 'hello => world');
// This should create array('hello' => array('world' => 'my value'))
$this->config->add('my value', 'hello => world => again');
// This should create array('hello' => array('world' => array('again' =>'my value')))

我在将'hello => world'转换为值设置为最后一个数组元素的数组时遇到问题。

这就是我到目前为止所拥有的。

    public function add($val, $key = null)
    {
        if (is_null($key))
        {
            $this->_config = $val;
        } else {
            $key = explode('=>', str_replace(' ', '', $key));
            if (count($key) > 1)
            {
                // ?
            } else {
                if (array_key_exists($key[0], $this->_config))
                {
                    $this->_config[$key[0]][] = $val;
                } else {
                    $this->_config[$key[0] = $val;
                }
            }
        }
    }
public function add($val, $key = null)
{
    $config=array();
    if (is_null($key))
    {
        $this->config = $val;
    } else {
        $key = explode('=>', str_replace(' ', '', $key));
        $current=&$this->config;
        $c=count($key);
        $i=0;
        foreach($key as $k)
        {
            $i++;
            if($i==$c)
            {
                $current[$k]=$val;
            }
            else
            {
                if(!isset($current[$k]) || !is_array($current[$k])) $current[$k]=array();
                $current=&$current[$k];
            }
        }
    }
}

这是一个递归版本,它将更昂贵的资源:

public function add($val, $key = null)
{
    $this->config=array();
    if (is_null($key))
    {
        $config = $val;
    } else {
        $key = array_reverse(explode('=>', str_replace(' ', '', $key)));
        self::addHelper($val,$key,$config);
    }
}
private static function addHelper(&$val,&$keys,&$current)
{
    $k=array_pop($keys);
    if(count($keys)>0)
    {
        if(!isset($current[$k]) || !is_array($current[$k])) $current[$k]=array();
        addHelper(&$val,$keys,&$current[$k]);
    }
    else $current[$k]=$val;
}

您可以尝试此操作,但它会擦除$this->_config 中的其他数据

... more code
if (count($key) > 1)
{
// ?
    $i = count($key) - 1;
    while($i >= 0) {
        $val = array($key[$i] => $val);
        $i--;
    }
    $this->_config = $val;
}
... more code