我試圖創建一個包含配置文件的數組,但我在遇到某些鍵具有相同名稱時遇到了麻煩。比方說,我有這種格式的配置:PHP:具有N個元素的動態多維數組
dinner=salad
dish.fruit.first.name=apple
dish.fruit.first.juicy=true
dish.fruit.second.name=lettuce
dish.fruit.second.juicy=false
dressing.name=french
dressing.tasty=true
,並會與想法變成一個數組這樣,可以有逗號的任何數量的分隔鍵值:
Array
(
[dinner] => "salad"
[dish] => Array
(
[fruit] => Array
(
[first] => Array
(
[name] => "apple"
[juicy] => "true"
)
[second] => Array
(
[name] => "lettuce"
[juicy] => "false"
)
)
)
[dressing] => Array
(
[name] => "french"
[tasty] => "true"
)
)
但我無法得到我的頭。我已經嘗試創建一個foreach循環,並通過引用將新數組插入到最後一個數組中,但只需要第一個以相同名稱開頭的密鑰集。這裏是我當前的代碼和結果:
$config = array();
$filehandle = @fopen($filename, "r");
while (!feof($filehandle))
{
$line = ereg_replace("/\n\r|\r\n|\n|\r/", "", fgets($filehandle, 4096));
$configArray = explode("=", $line);
$configKeys = explode(".", $configArray[0]);
$configValue = $configArray[1];
foreach ($configKeys as $key)
{
if (isset($head))
{
$last[$key] = array();
$last = &$last[$key];
}
else
{
$head[$key] = array();
$last = &$head[$key];
}
}
$last = $configValue;
$config += $head;
unset($head);
unset($last);
}
fclose($filehandle);
結果:
Array
(
[dinnes] => "salad"
[dish] => Array
(
[fruit] => Array
(
[first] => Array
(
[name] => "apple"
)
)
)
[dressing] => Array
(
[name] => "french"
)
)
您是否考慮過使用不同的配置文件格式?一個JSON對象將是微不足道的。 – 2011-06-02 21:53:39