0

Imagine having an array like this:

[
  'key1' => 'Label 1',
  'key2' => 'Label 2',
  'key3' => 'Label 3'
];

How can I convert that into a multidimensional array like this:

[
  'key1' => [
    'key1' => 'Label 1',
    'key2' => [
      'key2' => 'Label 2',
      'key3' => [
        'key3' => 'Label 3',
      ],
    ],
  ],
];

I thought about something with a recursive function and array_shift, but I'm not sure how to code it.

The array shall be nested as deep as there are elements.

2
  • Here's something similar, except it just creates the named keys, not the numeric ones in between: stackoverflow.com/questions/32522576/… Commented Nov 26, 2019 at 22:42
  • You don't need recursion, just a loop. Commented Nov 26, 2019 at 22:43

2 Answers 2

1

Here's a way to do it with a loop, maintaining a pointer into the output array so we can simply push values further into it:

$result = array();
$r = &$result;
foreach ($arr as $k => $v) {
    $r[$k] = array($k => $v);
    $r = &$r[$k];
}
print_r($result);

Output:

Array
(
    [key1] => Array
        (
            [key1] => Label 1
            [key2] => Array
                (
                    [key2] => Label 2
                    [key3] => Array
                        (
                            [key3] => Label 3
                        )
                )
        )
)

Demo on 3v4l.org

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

Comments

0

Here's a recursive solution just for fun:

function nest(array $flat): array
{
   // base
   if (!$flat) return [];

   // recursive
   return [key($flat) => array_merge(array_splice($flat, 0, 1), nest($flat))];
}

In the base case when the input is empty, you return an empty array.

For the recursive case you return a key/value pair with

  • key = the first key of the input and
  • value = the first element merged with the result of nesting the remaining elements

Comments

Your Answer

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