PHP converts a one-dimensional array to a multidimensional one

I have one array like

$tmpArr =  array('A', 'B', 'C');

I want to process this array and I want the new array to be

$tmpArr[A][B][C] = C

I. The last element becomes the value of the final array.

Can anyone suggest a solution? Please help. thanks in advance

+3
source share
3 answers

Iterate the key array and use reference to end the chain:

$arr = array();
$ref = &$arr;
foreach ($tmpArr as $key) {
    $ref[$key] = array();
    $ref = &$ref[$key];
}
$ref = $key;
$tmpArr = $arr;
+8
source
$tmpArr =  array('A', 'B', 'C');
$array = array();
foreach (array_reverse($tmpArr) as $arr)
      $array = array($arr => $array);

Conclusion:

Array
(
    [A] => Array
        (
            [B] => Array
                (
                    [C] => Array
                        (
                        )

                )

        )

)
+8
source
$tmpArr[$tmpArr[0]][$tmpArr[1]][$tmpArr[2]] = $tmpArr[2];

Is this what you want?

+2
source

Source: https://habr.com/ru/post/1766764/


All Articles