1. <?php
  2. /**
  3. * Flattens a nested configuration array.
  4. *
  5. * @param array $config The nested configuration array.
  6. * @param string $prefix The prefix for the flattened keys (optional).
  7. * @param array $flattened The flattened array (output).
  8. * @return array The flattened array.
  9. */
  10. function flattenConfig(array $config, string $prefix = '', array &$flattened = []): array
  11. {
  12. foreach ($config as $key => $value) {
  13. $newKey = $prefix ? $prefix . '.' . $key : $key;
  14. if (is_array($value)) {
  15. // Recursively flatten nested arrays
  16. flattenConfig($value, $newKey, $flattened);
  17. } else {
  18. // Add the key-value pair to the flattened array
  19. $flattened[$newKey] = $value;
  20. }
  21. }
  22. return $flattened;
  23. }
  24. // Example usage:
  25. /*
  26. $config = [
  27. 'server' => [
  28. 'host' => 'localhost',
  29. 'port' => 8080,
  30. ],
  31. 'database' => [
  32. 'host' => 'db.example.com',
  33. 'port' => 5432,
  34. 'user' => 'admin',
  35. 'password' => 'secure_password',
  36. ],
  37. 'logging' => [
  38. 'level' => 'info',
  39. 'file' => '/var/log/app.log',
  40. ],
  41. ];
  42. $flattenedConfig = flattenConfig($config);
  43. print_r($flattenedConfig);
  44. */
  45. ?>

Add your comment