我试图在 ini 设置文件中有一个嵌套的数组结构。我的结构是:
stuct1[123][a] = "1"
stuct1[123][b] = "2"
stuct1[123][c] = "3"
stuct1[123][d] = "4"
但这不起作用。谁能解释这种类型的结构是否可行parse_ini_file
如果可能的话,我做错了什么?
我试图在 ini 设置文件中有一个嵌套的数组结构。我的结构是:
stuct1[123][a] = "1"
stuct1[123][b] = "2"
stuct1[123][c] = "3"
stuct1[123][d] = "4"
但这不起作用。谁能解释这种类型的结构是否可行parse_ini_file
如果可能的话,我做错了什么?
您可以使用该任务的部分功能parse_ini_file
。
请务必将第二个参数设置为true
:
parse_ini_file("sample.ini", true);
创建子部分并不完全可能,但您可以像这样创建索引子数组:
[123]
setting[] = "1"
setting[] = "2"
setting[] = "3"
setting[] = "4"
解析它看起来像thos
[123][setting][0] => "1"
[123][setting][1] => "2"
[123][setting][2] => "3"
[123][setting][3] => "4"
您最多可以创建三个级别。
<?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"
输出
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
)
)
)
INI 文件非常有限,并且 parse_ini_file 远非完美。如果你有这样的要求,你最好寻找一些其他的语法。
那么JSON呢?它在 PHP 中的支持带来了几乎相同的舒适度:
$data = json_decode(file_get_contents($filename), TRUE);
file_put_contents($filename, json_encode($data));
这是在 ini 中对值进行分组的另一种方法:
我的.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
我的.php:
与以下相同:
<?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'; ?>
这也适用于 bool 设置为 true ,可用于循环。也适用于设置为 true 的 bool。
http://php.net/manual/en/function.parse-ini-file.php
张贴者大卫点染料在 gmail dot com 4 年前