<?php
/**
* Flattens a nested configuration array.
*
* @param array $config The nested configuration array.
* @param string $prefix The prefix for the flattened keys (optional).
* @param array $flattened The flattened array (output).
* @return array The flattened array.
*/
function flattenConfig(array $config, string $prefix = '', array &$flattened = []): array
{
foreach ($config as $key => $value) {
$newKey = $prefix ? $prefix . '.' . $key : $key;
if (is_array($value)) {
// Recursively flatten nested arrays
flattenConfig($value, $newKey, $flattened);
} else {
// Add the key-value pair to the flattened array
$flattened[$newKey] = $value;
}
}
return $flattened;
}
// Example usage:
/*
$config = [
'server' => [
'host' => 'localhost',
'port' => 8080,
],
'database' => [
'host' => 'db.example.com',
'port' => 5432,
'user' => 'admin',
'password' => 'secure_password',
],
'logging' => [
'level' => 'info',
'file' => '/var/log/app.log',
],
];
$flattenedConfig = flattenConfig($config);
print_r($flattenedConfig);
*/
?>
Add your comment