如何在PHP中将数组元素作为数组?

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] => 
                                                        )

                                                )

                                        )

                                )

                        )

                )

        )

}

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.

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.