Parse .ini file with flat keys to multidimensional array
I wanted to convert an array, based on an .ini file, with a pattern in flat keys to a multidimensional array. I found this post Convert Flat PHP Array to Nested Array based on Array Keys and made the following modification.
<?php
$db_settings = parse_ini_file($_SERVER['DOCUMENT_ROOT'].'/website/var/config/app.ini');
/**
* Give it and array, and an array of parents, it will decent into the
* nested arrays and set the value.
*/
function set_nested_value(array &$arr, array $ancestors, $value) {
$current = &$arr;
foreach ($ancestors as $key) {
// To handle the original input, if an item is not an array,
// replace it with an array with the value as the first item.
if (!is_array($current)) {
$current = array( $current);
}
if (!array_key_exists($key, $current)) {
$current[$key] = array();
}
$current = &$current[$key];
}
$current = $value;
}
//$education = array(
// 'resources.db.adapter' => 'Georgia Tech',
// 'x[1][1]' => 'Mechanical Engineering',
// 'x[1][2]' => 'Computer Science',
// 'x[2]' => 'Agnes Scott',
// 'x[2][1]' => 'Religious History',
// 'x[2][2]' => 'Women\'s Studies',
// 'x[3]' => 'Georgia State',
// 'x[3][1]' => 'Business Administration',
//);
I had this setup in my array, based on an .ini file:
[resources.db.adapter] => PDO_MYSQL
[resources.db.params.host] => localhost
[resources.db.params.dbname] => qwer
[resources.db.params.username] => asdf
[resources.db.params.password] => zxcv
[resources.db.params.charset] => utf8
[externaldb.adapter] => PDO_MYSQL
[externaldb.params.host] => localhost
[externaldb.params.dbname] => tyui
[externaldb.params.username] => ghjk
[externaldb.params.password] => vbnm
[externaldb.params.charset] => latin1
$neweducation = array();
foreach ($db_settings as $path => $value) {
//$ancestors = explode('][', substr($path, 2, -1));
$ancestors = explode('.', $path);
set_nested_value($neweducation, $ancestors, $value);
}
echo "<pre>";
print_r($neweducation);
echo "</pre>";
echo __FILE__ . __LINE__; // exit;
?>
The outcome became as desired:
Array
(
[resources] => Array
(
[db] => Array
(
[adapter] => PDO_MYSQL
[params] => Array
(
[host] => localhost
[dbname] => qwer
[username] => asdf
[password] => zxcv
[charset] => utf8
)
)
)
[externaldb] => Array
(
[adapter] => PDO_MYSQL
[params] => Array
(
[host] => localhost
[dbname] => tyui
[username] => ghjk
[password] => vbnm
[charset] => latin1
)
)
)Knowledge keywords:
