Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested arrays in ini file

Tags:

php

I am trying to have a nested array structure inside an ini settings file. The structure i have is:

stuct1[123][a] = "1"
stuct1[123][b] = "2"
stuct1[123][c] = "3"
stuct1[123][d] = "4"

But this doesnt work. Can anyone explain if this type of structure is possible with parse_ini_file

If it is possible, what am i doing wrong?

like image 388
Marty Wallace Avatar asked Jan 30 '13 22:01

Marty Wallace


3 Answers

You can use the sections feature of parse_ini_file for this task.

Be sure to set your second parameter to true:

parse_ini_file("sample.ini", true);

It's not exactly possible to make sub sections but you can make an indexed sub array like this:

[123]
setting[] = "1"
setting[] = "2"
setting[] = "3"
setting[] = "4"

Parsed it would look similar like thos

[123][setting][0] => "1"
[123][setting][1] => "2"
[123][setting][2] => "3"
[123][setting][3] => "4"
like image 114
dan-lee Avatar answered Nov 15 '22 22:11

dan-lee


You can create a hard maximum of three levels.

<?php

define('BIRD', 'Dodo bird');

$ini_array = parse_ini_file("sample.ini", true);
echo '<pre>'.print_r($ini_array,true).'</pre>';

?>

parse_ini_file.ini

; This is a sample configuration file
; Comments start with ';', as in php.ini

[first_section]
one = 1
five = 5
animal = BIRD

[second_section]
path = "/usr/local/bin"
URL = "http://www.example.com/~username"
second_section[one] = "1 associated"
second_section[two] = "2 associated"
second_section[] = "1 unassociated"
second_section[] = "2 unassociated"

[third_section]
phpversion[] = "5.0"
phpversion[] = "5.1"
phpversion[] = "5.2"
phpversion[] = "5.3"

Output

Array (

    [first_section] => Array (
        [one] => 1
        [five] => 5
        [animal] => Dodo bird
    )

    [second_section] => Array (
        [path] => /usr/local/bin
        [URL] => http://www.example.com/~username
        [second_section] => Array (
            [one] => 1 associated
            [two] => 2 associated
            [0] => 1 unassociated
            [1] => 2 unassociated
        )
    )

    [third_section] => Array (
        [phpversion] => Array (
            [0] => 5.0
            [1] => 5.1
            [2] => 5.2
            [3] => 5.3
        )
    )
    
)
like image 17
user1032531 Avatar answered Nov 15 '22 21:11

user1032531


INI files are pretty limited and parse_ini_file is far from perfect. If you have requirements like this, you should better look for some other syntax.

What about JSON? It's support in PHP comes with almost same comfort:

$data = json_decode(file_get_contents($filename), TRUE);
file_put_contents($filename, json_encode($data));
like image 5
Josef Kufner Avatar answered Nov 15 '22 20:11

Josef Kufner