我有下一个INI文件:
a.b.c = 1
a.b.d.e = 2
我正在使用parse_ini_file解析此文件。它返回:
array(
'a.b.c' => 1,
'a.b.d.e' => 2
)
但我想创建一个多维数组。我的外出应该是:
array(
'a' => array(
'b' => array(
'c' => 1,
'd' => array(
'e' => 2
)
)
)
)
提前谢谢。
答案 0 :(得分:5)
这就是我的看法:
<?php
class ParseIniMulti {
public static function parse($filename) {
$ini_arr = parse_ini_file($filename);
if ($ini_arr === FALSE) {
return FALSE;
}
self::fix_ini_multi(&$ini_arr);
return $ini_arr;
}
private static function fix_ini_multi(&$ini_arr) {
foreach ($ini_arr AS $key => &$value) {
if (is_array($value)) {
self::fix_ini_multi($value);
}
if (strpos($key, '.') !== FALSE) {
$key_arr = explode('.', $key);
$last_key = array_pop($key_arr);
$cur_elem = &$ini_arr;
foreach ($key_arr AS $key_step) {
if (!isset($cur_elem[$key_step])) {
$cur_elem[$key_step] = array();
}
$cur_elem = &$cur_elem[$key_step];
}
$cur_elem[$last_key] = $value;
unset($ini_arr[$key]);
}
}
}
}
var_dump(ParseIniMulti::parse('test.ini'));
答案 1 :(得分:4)
实际上非常简单,你只需要通过爆炸它的关键来改变你已经拥有的数组的格式:
$ini_preparsed = array(
'a.b.c' => 1,
'a.b.d.e' => 2
);
$ini = array();
foreach($ini_preparsed as $key => $value)
{
$p = &$ini;
foreach(explode('.', $key) as $k)
$p = &$p[$k];
$p = $value;
}
unset($p);
print_r($ini);
输出:
Array
(
[a] => Array
(
[b] => Array
(
[c] => 1
[d] => Array
(
[e] => 2
)
)
)
)
答案 2 :(得分:2)
查看Zend_Config_Ini课程。它做你想要的,你可以独立使用它(没有Zend Framework的其余部分),作为奖励,它支持部分继承。
使用toArray
方法,您可以从配置对象创建一个数组。
答案 3 :(得分:2)
看看PHProp。
与Zend_Config_Ini
类似,但您可以在配置中引用密钥,例如${key}
答案 4 :(得分:0)
这是一个将config ini文件解析为多维数组的类:
class Cubique_Config {
const SEPARATOR = '.';
private static $_data = null;
public static function get() {
if (is_null(self::$_data)) {
$commonIniFile = APP . '/config' . '/common.ini';
$envIniFile = APP . '/config' . '/' . ENV . '.ini';
if (!file_exists($commonIniFile)) {
throw new Exception('\'' . $commonIniFile . '\' config file not found');
}
if (!file_exists($envIniFile)) {
throw new Exception('\'' . $envIniFile . '\' config file not found');
}
$commonIni = parse_ini_file($commonIniFile);
$envIni = parse_ini_file($envIniFile);
$mergedIni = array_merge($commonIni, $envIni);
self::$_data = array();
foreach ($mergedIni as $rowKey => $rowValue) {
$explodedRow = explode(self::SEPARATOR, $rowKey);
self::$_data = array_merge_recursive(self::$_data, self::_subArray($explodedRow, $rowValue));
}
}
return self::$_data;
}
private static function _subArray($explodedRow, $value) {
$result = null;
$explodedRow = array_values($explodedRow);
if (count($explodedRow)) {
$firstItem = $explodedRow[0];
unset($explodedRow[0]);
$result[$firstItem] = self::_subArray($explodedRow, $value);
} else {
$result = $value;
}
return $result;
}
}