php create multidimensional array from flat one

后端 未结 5 2035
时光说笑
时光说笑 2020-12-18 11:21

I have an array like this:

 \'foo\', 1 => \'bar\', ..., x => \'foobar\' );
?>

What is the fas

5条回答
  •  心在旅途
    2020-12-18 12:17

    I'm confused about what you want to do with non-numeric keys (ie, x in your example). But in any case using array references will help

    $array = array( 0 => 'foo', 1 => 'bar',  x => 'foobar' );
    
    
    $out = array();
    $curr = &$out;
    
    foreach ($array as $key => $value) {
        $curr[$value] = array(); 
        $curr = &$curr[$value];
    }
    
    print( "In: \n" );
    print_r($array);
    print( "Out : \n" );
    print_r($out);
    

    Prints out

    In:
    Array
    (
        [0] => foo
        [1] => bar
        [x] => foobar
    )
    Out :
    Array
    (
        [foo] => Array
            (
                [bar] => Array
                    (
                        [foobar] => Array
                            (
                            )
    
                    )
    
            )
    
    )
    

提交回复
热议问题