Nilesh
Nilesh

Reputation: 1087

PHP convert one dimensional array into multidimensional

I have one array as

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

I want to process this array and want new array as

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

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

Can anyone suggest the solution? Please help. Thanks in advance

Upvotes: 3

Views: 9985

Answers (3)

Russell Dias
Russell Dias

Reputation: 73402

$tmpArr =  array('A', 'B', 'C');
$array = array();
foreach (array_reverse($tmpArr) as $arr)
      $array = array($arr => $array);

Output:

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

                )

        )

)

Upvotes: 10

Gumbo
Gumbo

Reputation: 655845

Iterate the array of keys and use a reference for the end of the chain:

$arr = array();
$ref = &$arr;
foreach ($tmpArr as $key) {
    $ref[$key] = array();
    $ref = &$ref[$key];
}
$ref = $key;
$tmpArr = $arr;

Upvotes: 10

Tokk
Tokk

Reputation: 4502

$tmpArr[$tmpArr[0]][$tmpArr[1]][$tmpArr[2]] = $tmpArr[2];

Is that what you want?

Upvotes: 2

Related Questions