Okay this might be confusing. I’m trying to make a config class for myself and I want its usage to be something like this:
$this->config->add('world', 'hello');
// This will create array('hello' => 'world')
Now my question is, if I want to add my value into a multi-dimensional array that doesn’t exists but would like to create it using something like this:
$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')))
I’m having trouble converting 'hello => world' into an array with the value set to the last array element.
This is what I have so far.
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;
}
}
}
}
Here’s a recursive version, It will be more resource-expensive: