I thought about it a lot before posting this question.
The question is more conceptual than anything else.
Starting from a classic array, I want to dynamically transform it into multidinamic with subtrees.
to be clear, from this:
$array = ['my', 'unique', 'values', 'array', 'and', 'so', 'on', '...'];
to this:
Array
(
['my'] =>
['unique'] =>
['values'] =>
['array'] =>
['and'] =>
['so'] =>
['on']=>
['...'] => []
)
The only attempt I made was "barbarously" to dynamically create strings and pass them with the eval()
command.
I don't write the code here for personal dignity. It's bad enough I confessed it. Insiders will understand...
I fully believe that there is a correct way to do it, but of course, if I'm here, I don't know it
Best
Oscar
Start from the end and end with the start:
$length = sizeof($array);
$value = [];
for ($index = $length - 1; $index >= 0; $index--) {
$value = [
"{$array[$index]}" => $value
];
unset($array[$index]);
}
$array[]=$value;
This uses references to keep track of what element you are currently adding the data to, so to start $add
is the root element (by setting it to &$newArray
). Each time it adds a new level it moves the reference to this new item (with &$add[$key]
) and repeats the process...
$array = ['my', 'unique', 'values', 'array', 'and', 'so', 'on', '...'];
$newArray = [];
$add = &$newArray;
foreach ( $array as $key ) {
$add[$key] = [];
$add = &$add[$key];
}
print_r($newArray);
Or another option is to create the structure from the outside in using a while loop and decreasing the index on every iteration.
Temporary store what you already have and reset the current $result
. Then add an entry with a new key and add the temporary stored variable as the value.
$array = ['my', 'unique', 'values', 'array', 'and', 'so', 'on'];
$result = [];
$tot = count($array) - 1;
while ($tot > -1) {
$temp = $result;
$result = [];
$result[$array[$tot]] = $temp;
$tot--;
}
print_r($result);