ini文件中的嵌套数组

Mar*_*ace 8 php

我试图在ini设置文件中有一个嵌套的数组结构.我的结构是:

stuct1[123][a] = "1"
stuct1[123][b] = "2"
stuct1[123][c] = "3"
stuct1[123][d] = "4"
Run Code Online (Sandbox Code Playgroud)

但这不起作用.任何人都可以解释这种结构是否可行parse_ini_file

如果有可能,我做错了什么?

Dan*_*Lee 41

您可以使用部分功能parse_ini_file完成这个任务.

务必将第二个参数设置为true:

parse_ini_file("sample.ini", true);
Run Code Online (Sandbox Code Playgroud)

制作子节目并不完全可能,但你可以制作一个像这样的索引子数组:

[123]
setting[] = "1"
setting[] = "2"
setting[] = "3"
setting[] = "4"
Run Code Online (Sandbox Code Playgroud)

解析它看起来像thos

[123][setting][0] => "1"
[123][setting][1] => "2"
[123][setting][2] => "3"
[123][setting][3] => "4"
Run Code Online (Sandbox Code Playgroud)

  • 这应该是公认的答案,因为它完全解决了问题,而不是替代解决方案 (13认同)

use*_*531 13

您可以创建至少三个级别.也许更多,但我不知道该怎么做.

<?php

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

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

?>
Run Code Online (Sandbox Code Playgroud)

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"
Run Code Online (Sandbox Code Playgroud)

产量

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
                )

        )

)
Run Code Online (Sandbox Code Playgroud)


Jos*_*ner 5

INI 文件非常有限, parse_ini_file 远非完美。如果你有这样的要求,你最好寻找一些其他的语法。

什么JSON?它在 PHP 中支持带来了几乎相同的舒适度:

$data = json_decode(file_get_contents($filename), TRUE);
file_put_contents($filename, json_encode($data));
Run Code Online (Sandbox Code Playgroud)

  • 应该补充一点,ini 文件应该是人类可写和机器可读的。JSON 文件应该是机器可写和人类可读的。它们在语法方面非常严格,微小的错误都会导致整个 json 文件无效。ini 文件中几乎没有错误会使文件无效,只有行。 (3认同)