PHP convert one dimensional array into multidimensional

依然范特西╮ 提交于 2019-12-30 03:33:16

问题


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


回答1:


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;



回答2:


$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
                        (
                        )

                )

        )

)



回答3:


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

Is that what you want?



来源:https://stackoverflow.com/questions/3804062/php-convert-one-dimensional-array-into-multidimensional

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!