I'm trying to create an array that contains a config file, but I'm having trouble when some of the keys has the same name. Let's say I have a config in this kind of format:
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
and that would be turned into an array like this with the idea, that there can be any amount of comma seperated key values:
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"
)
)
But I'm unable to get my head around it. I've tried creating a foreach loop and inserting new array into the last array via references, but it takes only the first key set starting with same name. Here's my current code and the result:
$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);
result:
Array
(
[dinnes] => "salad"
[dish] => Array
(
[fruit] => Array
(
[first] => Array
(
[name] => "apple"
)
)
)
[dressing] => Array
(
[name] => "french"
)
)