2

How to convert this* string:

$arrKeys = ['lev1', 'lev2', 'lev3'];
$val = 'foo';

In to the following array:

Array
(
[lev1] => Array
    (
        [lev2] => Array
            (
                [lev3] => foo
            )

    )
)

*Number of array keys may vary. Each array key except the last one represents Array.

Thank you!

Jiri Mihal
  • 432
  • 3
  • 11

3 Answers3

4

No recursion necessary:

$arrKeys = array_reverse(['lev1', 'lev2', 'lev3']);
$val = 'foo';

$result = $val;

foreach ($arrKeys as $key) {
    $result = [$key => $result];
}

print_r($result); 

// Array
// (
//     [lev1] => Array
//     (
//         [lev2] => Array
//         (
//             [lev3] => foo
//         )
// 
//     )
// 
// )

Just build the array from the inside out.

Pieter van den Ham
  • 4,381
  • 3
  • 26
  • 41
2

Here's one way you can do it with a recursive function. This is my personal favourite because it has very good readability.

function nest(array $keys, $value) {
  if (count($keys) === 0)
    return $value;
  else
    return [$keys[0] => nest(array_slice($keys, 1), $value)];
}

$result = nest(['key1', 'key2', 'key3'], 'foo');

print_r($result);

// Array
// (
//     [key1] => Array
//         (
//             [key2] => Array
//                 (
//                     [key3] => foo
//                 )
//         )
// )

Or another way you can do it using array_reduce. This way is also quite nice but there's a little added complexity here because the array of keys has to be reversed first.

function nest(array $keys, $value) {
  return array_reduce(array_reverse($keys), function($acc, $key) {
    return [$key => $acc];
  }, $value);
}

$result = nest(['key1', 'key2', 'key3'], 'foo');

print_r($result);

// Array
// (
//     [key1] => Array
//         (
//             [key2] => Array
//                 (
//                     [key3] => foo
//                 )
//         )
// )

Both solutions work for any number of keys. Even if $keys is an empty array

nest([], 'foo'); //=> 'foo'
Mulan
  • 129,518
  • 31
  • 228
  • 259
1

This is a pretty similar approach to the other iterative answer, but pops values off the end of the $arrKeys array rather than reversing it at the beginning.

$result = $val;    // start with the innermost value

while ($level = array_pop($arrKeys)) {
    $result = [$level => $result];      // build out using each key as a new level
}
Don't Panic
  • 41,125
  • 10
  • 61
  • 80