1

Given that I have my array in this form:

$x = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h');

How can I get it in the following format?

Array
(
    [h] => Array
        (
            [g] => Array
                (
                    [f] => Array
                        (
                            [e] => Array
                                (
                                    [d] => Array
                                        (
                                            [c] => Array
                                                (
                                                    [b] => Array
                                                        (
                                                            [a] => 
                                                        )

                                                )

                                        )

                                )

                        )

                )

        )

}
Cᴏʀʏ
  • 105,112
  • 20
  • 162
  • 194
Raftko
  • 33
  • 1
  • 4
  • look here for example = http://stackoverflow.com/questions/37659106/how-dynamically-create-array-in-php-with-string-index/37659231#37659231 – splash58 Jun 23 '16 at 17:16
  • @splash58 - `explode()` takes a string, not an array, so whatever you're suggesting as the solution here is not abundantly clear. – devlin carnate Jun 23 '16 at 17:18

2 Answers2

3

Like this:

$x = array_reverse($x);
$a = array();
$r =& $a;
foreach($x as $y) {
    $r[$y] = [];
    $r =& $r[$y];
}
print_r($a);

This code just adds an array to a previously created array. It uses a reference to the last created array to keep track of where to add yet another array.

It is a little difficult to explain, but read about references in PHP and you should get it.

Sverri M. Olsen
  • 13,055
  • 3
  • 36
  • 52
2

You can obtain this via array_reduce, which walks through the array and applies the reducing function to each element:

$y = array_reduce($x, function($acc, $item) {
    return [$item => $acc];
}, '');

Given the nature of the reduce operation, you don't need to reverse the array, as each element will embed the array of the preceding ones, resulting in the multi-level array you need.

Note. I assumed that you want at the last level an empty string, but you can have there anything you want. Just update the third parameter passed to array_reduce with the value you need to have at the last level.

Cristik
  • 30,989
  • 25
  • 91
  • 127