PHP One level deeper in array each loop made

前端 未结 4 2098
旧巷少年郎
旧巷少年郎 2021-01-15 17:49

I\'m trying to loop through one array, adding a new level to another array each time. Let me illustrate - variable $arr\'s values are different each time

$ar         


        
4条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-15 18:23

    You can use references here:

    $a = array("1","5","6");
    $b = array();
    $c =& $b;
    
    foreach ($a as $k) {
        $c[$k] = array();
        $c     =& $c[$k];
    }
    

    outputs

    Array 
        (
        [1] => Array
            (
                [5] => Array
                    (
                        [6] => Array
                            (
                            )
                    )
            )
    )
    

    To overwrite the last element with some other value, you can just add the line:

    $c = 'blubber';
    

    after the loop, because $c is a reference to the deepest array level, when the loop is finished.

提交回复
热议问题