INI file to multidimensional array in PHP

前端 未结 5 1760
花落未央
花落未央 2021-01-18 08:51

I have the next INI file:

a.b.c = 1
a.b.d.e = 2

I am parsing this file using parse_ini_file. And it returns:

array(
    \'a         


        
5条回答
  •  [愿得一人]
    2021-01-18 09:54

    It's actually quite simple, you only need to change the format of the array you already have by exploding it's key:

    $ini_preparsed = array(
        'a.b.c' => 1,
        'a.b.d.e' => 2
    );
    
    
    $ini = array();
    foreach($ini_preparsed as $key => $value)
    {
        $p = &$ini;
        foreach(explode('.', $key) as $k)
            $p = &$p[$k];
        $p = $value;
    }
    unset($p);
    
    print_r($ini);
    

    Output:

    Array
    (
        [a] => Array
            (
                [b] => Array
                    (
                        [c] => 1
                        [d] => Array
                            (
                                [e] => 2
                            )
    
                    )
    
            )
    
    )
    

    See as well: String with array structure to Array.

提交回复
热议问题