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][
Here is another way to group values in the ini:
my.ini:
[singles] test = a test test2 = another test test3 = this is a test too [multiples] tests[] = a test tests[] = another test tests[] = this is a test too
my.php:
The same as:
<?php $init['test'] = 'a test'; $init['test2'] = 'another test'; $init['test3'] = 'this is a test too'; $init['tests'][0] = 'a test'; $init['tests'][1] = 'another test'; $init['tests'][2] = 'this is a test too'; ?>
This works with the bool set to true also, can be useful with loops. Works with the bool set to true as well.
http://php.net/manual/en/function.parse-ini-file.php
Posted by david dot dyess at gmail dot com 4 years ago
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));
You can create a minimum of three levels. Maybe more, but I don't know how to do so.
<?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
)
)
)
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"