2

The main idea is that I want to convert this array:

$arr1 = ['user', 'address', 'street'];

To this one:

$arr2['user']['address']['street'];

I've been trying with recursive functions, foreach, for... but I couldn't figure out how to do it.

Example:

function appendingArrays($arrayOfKeys, $value) {
    // TODO
}
$finalArray = appendingArrays(['user', 'address', 'street'], 'Lombard Street');

echo $finalArray['user']['address']['street']; // Lombard Street

Any idea?

Lenik
  • 63
  • 5
  • https://stackoverflow.com/questions/10519108/split-a-string-to-form-multidimensional-array-keys, https://stackoverflow.com/questions/31103719/php-make-a-multidimensional-associative-array-from-key-names-in-a-string-separat, https://stackoverflow.com/questions/37356391/php-explode-string-key-into-multidimensional-array-with-values – 04FS Oct 08 '20 at 11:47

1 Answers1

2

Hope this helps : Go Through Demo

[akshay@db1 tmp]$ cat test.php 
<?php

$arr1 = ['user', 'address', 'street'];

$c = count($arr1) - 1;
$out = array();
for($i = $c; $i >= 0; $i--)
{
    $out = array($arr1[$i] => $out);
}

/* input */  
print_r($arr1);

/* output */
print_r($out);

Output:

[akshay@db1 tmp]$ php test.php 
Array
(
    [0] => user
    [1] => address
    [2] => street
)
Array
(
    [user] => Array
        (
            [address] => Array
                (
                    [street] => Array
                        (
                        )

                )

        )

)
Akshay Hegde
  • 16,536
  • 2
  • 22
  • 36