Anonymous Anonymous - 1 year ago 70
PHP Question

Turn array values from a single dimension array into the depth of another array

So lets say I have the following array:

$value = 'x';

$foo = Array(
0 => 'arraydepth1',
1 => 'arraydepth2',
2 => 'arraydepth3',
3 => 'arraydepth4'
)


I need the values to be the keys, in order/depth, of the following array:

$bar['arraydepth1']['arraydepth2']['arraydepth3']['arraydepth4'] = 'x';

Answer

Wrap you head around this:

function nest(Array $a, $lastValue) {
    $out = [];
    $ref =& $out;
    foreach ($a as $b) {
        $ref[$b] = [];
        $ref =& $ref[$b];
    }
    $ref = $lastValue;
    return $out;
}
var_dump(nest($foo, $value));

It is a little convoluted to explain, but here is my attempt:

  • The $out variable is just an array that is going to be returned at the end of the function.

  • $ref is a reference to the most recently nested array.

  • In the loop we keep adding an array to the reference and then setting the reference to the added array.