4

I've some difficulties creating a nested array by array of keys and assigning a value for the last nested item.

For example, lets $value = 4; and $keys = ['a', 'b', 'c'];

The final result should be:

[
  'a' => [
    'b' => [
      'c' => 4
    ]
  ]
]

I've tried with a recursion, but without success. Any help would be greatly appreciated.

  • 3
    @AbraCadaver, the other question you mention as duplicate is the exact complementer of this question. Here he asked how to create the nested array from a different input format, there the nested array is given as input. – Gavriel Jan 19 '16 at 21:08
  • Dupe has been edited. – AbraCadaver Jan 05 '17 at 16:27

3 Answers3

7

you don't need recursion, just do it from the right to left:

$a = $value;
for ($i = count($keys)-1; $i>=0; $i--) {
  $a = array($keys[$i] => $a);
}

or the even shorter version from @felipsmartins:

$a = $value;
foreach (array_reverse($keys) as $valueAsKey) $a = [$valueAsKey => $a]; 
Gavriel
  • 18,880
  • 12
  • 68
  • 105
  • That was too easy... Thanks @Gavriel –  Jan 19 '16 at 20:17
  • This output Array ( [b] => Array ( [c] => 4 ) ) – Jakir Hossain Jan 19 '16 at 20:43
  • 2
    Pretty good! But it could be somewhat more "*easy to catch*" like this: [gist snippet](https://gist.github.com/felipsmartins/b8a5a8f7a8547506c5a7) – felipsmartins Jan 19 '16 at 22:35
  • 1
    What you mean by "easy to catch"? (you meant "easier to understand"?) – imho just renaming `$a` to `$new` doesn't improve much ("new" what?). Also you could as well have edited Gabriel's answer, so everybody would benefit from it. – Kamafeather Feb 28 '23 at 19:54
1

Your can try it.

$value = 4;
$keys = ['a', 'b', 'c'];
$a = $value;
$i=count($keys)-1;
foreach($keys as $key){
    $a = array($keys[$i] => $a);
    $i--;
}
print_r($a);

Output

Array
(
    [a] => Array
        (
            [b] => Array
                (
                    [c] => 4
                )

        )

)
Jakir Hossain
  • 2,457
  • 18
  • 23
0

Solution by getting a nested item in the resulting array by reference:

$value = 4;
$keys = ['a', 'b', 'c'];

$result = [];

$reference = &$result;
foreach($keys as $key) {
    if (!array_key_exists($key, $reference)) $reference[$key] = [];
    $reference = &$reference[$key];
}
$reference = $value;

print_r($result);