3

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

3 Answers 3

5

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);
Sign up to request clarification or add additional context in comments.

1 Comment

I realize to be a duffer. Thanks
2

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);

Php demo

Comments

1

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;

2 Comments

Vote up without needing to test the code. It was enough for me to have read it. Low level code, as I like it. More than "thank you", I congratulate you !!!
You don't really need the unset(), just overwrite the array at the end - $array=$value;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.