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!

1

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

And of course many thanks to all others. I appreciate your time.
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'

Comments

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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.