Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

INI file to multidimensional array in PHP

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.b.c' => 1,
    'a.b.d.e' => 2
)

But I want to create a multidimensional array. My outout should be:

array(
    'a' => array(
        'b' => array(
            'c' => 1,
            'd' => array(
                'e' => 2
            )
        )
    )
)

Thank you in advance.

like image 323
Alex Pliutau Avatar asked Sep 20 '11 06:09

Alex Pliutau


3 Answers

This is how I see it:

<?php

class ParseIniMulti {

    public static function parse($filename) {
        $ini_arr = parse_ini_file($filename);
        if ($ini_arr === FALSE) {
            return FALSE;
        }
        self::fix_ini_multi(&$ini_arr);
        return $ini_arr;
    }

    private static function fix_ini_multi(&$ini_arr) {
        foreach ($ini_arr AS $key => &$value) {
            if (is_array($value)) {
                self::fix_ini_multi($value);
            }
            if (strpos($key, '.') !== FALSE) {
                $key_arr = explode('.', $key);
                $last_key = array_pop($key_arr);
                $cur_elem = &$ini_arr;
                foreach ($key_arr AS $key_step) {
                    if (!isset($cur_elem[$key_step])) {
                        $cur_elem[$key_step] = array();
                    }
                    $cur_elem = &$cur_elem[$key_step];
                }
                $cur_elem[$last_key] = $value;
                unset($ini_arr[$key]);
            }
        }
    }

}


var_dump(ParseIniMulti::parse('test.ini'));
like image 59
XzKto Avatar answered Sep 28 '22 09:09

XzKto


Have a look at the Zend_Config_Ini class. It does what you want, you can use it standalone (without the rest of Zend Framework) and as a bonus it supports section inheritance.

With the toArray method you can create an array from the config object.

like image 45
chiborg Avatar answered Sep 28 '22 08:09

chiborg


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.

like image 44
hakre Avatar answered Sep 28 '22 09:09

hakre