0

I have a pretty simple problem, but for now, I can't seem to wrap my head around it.

I have a 1D array, for example:

$array = array("file", "video", "url")

And I want to convert it to:

$array["file"]["video"]["url"] = array();

Now, I won't know in advance how many elements I will have in my first array so I cannot make any assumptions. Also, I cannot use a tree structure for this particular problem, it needs to be an array.

2 Answers 2

4

Elegantly, using recursion

function nested($keys, $value) {
    return $keys ?
        array($keys[0] => nested(array_slice($keys, 1), $value))
        : $value;
}

print_r(nested(array("file", "video", "url"), 42));
Sign up to request clarification or add additional context in comments.

1 Comment

Ahhh 42, the value to the ultimate question of life, the universe, and everything... :)
2

Fairly straightforward to build

$array = array("file", "video", "url");

$newArray = array();
$newEntry = &$newArray;
foreach($array as $value) {
    $newEntry[$value] = array();
    $newEntry = &$newEntry[$value];
}
unset($newEntry);
var_dump($newArray);

Comments

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.