dimanche 22 février 2015

PHP explode string into multidimensional array [duplicate]


I have strings like Foo::Bar::Baz and need to transform them into keys of an multidimensional associative array like this $arr['Foo']['Bar']['Baz'] = 'some value'


The problem is that the number of parts can vary. So I need to find a solution to explode the parts into the keys of an multidimensional array.


My current solution looks like this



function write($key, $value)
{
$parts = explode("::", $key);
if (count($parts) == 1) {
$this->body[$parts[0]] = $value;
} elseif (count($parts) == 2) {
$this->body[$parts[0]][$parts[1]] = $value;
} elseif (count($parts) == 3) {
$this->body[$parts[0]][$parts[1]][$parts[2]] = $value;
}
}


It works but is very redundant and it only supports three parts.


Is there a way to automatically explode the parts into the keys of an array?


Aucun commentaire:

Enregistrer un commentaire