在某些非常特殊的情况下,您可能希望在您的 ini 文件中解析具有 N 级别的多维数组。例如,设置[data][config][debug] = true 会导致错误(预期“=”)。
以下是一个使用点(可自定义)来匹配此功能的小函数。
<?php
function parse_ini_file_multi($file, $process_sections = false, $scanner_mode = INI_SCANNER_NORMAL) {
$explode_str = '.';
$escape_char = "'";
$data = parse_ini_file($file, $process_sections, $scanner_mode);
if (!$process_sections) {
$data = array($data);
}
foreach ($data as $section_key => $section) {
foreach ($section as $key => $value) {
if (strpos($key, $explode_str)) {
if (substr($key, 0, 1) !== $escape_char) {
$sub_keys = explode($explode_str, $key);
$subs =& $data[$section_key];
foreach ($sub_keys as $sub_key) {
if (!isset($subs[$sub_key])) {
$subs[$sub_key] = [];
}
$subs =& $subs[$sub_key];
}
$subs = $value;
unset($data[$section_key][$key]);
}
else {
$new_key = trim($key, $escape_char);
$data[$section_key][$new_key] = $value;
unset($data[$section_key][$key]);
}
}
}
}
if (!$process_sections) {
$data = $data[0];
}
return $data;
}
?>
以下文件
<?php
?>
将生成以下结果
<?php
parse_ini_file_multi('file.ini', true);
Array
(
[normal] => Array
(
[foo] => bar
[foo.with.dots] => 1
)
[array] => Array
(
[foo] => Array
(
[0] => 1
[1] => 2
)
)
[dictionary] => Array
(
[foo] => Array
(
[debug] =>
[path] => /some/path
)
)
[multi] => Array
(
[foo] => Array
(
[data] => Array
(
[config] => Array
(
[debug] => 1
)
[password] => 123456
)
)
)
)
?>