Etienne Noël
Etienne Noël

Reputation: 6176

Convert 1d array to multidimensional array

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.

Upvotes: 0

Views: 363

Answers (2)

georg
georg

Reputation: 215059

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

Upvotes: 4

Mark Baker
Mark Baker

Reputation: 212522

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

Upvotes: 2

Related Questions