1. <?php
  2. /**
  3. * Flattens a nested array structure with basic input validation.
  4. *
  5. * @param array $data The input array to flatten.
  6. * @return array The flattened array. Returns an empty array on invalid input.
  7. */
  8. function flattenArray(array $data): array
  9. {
  10. if (!is_array($data)) {
  11. return []; // Handle non-array input.
  12. }
  13. $flattened = [];
  14. function flatten(array $arr, string $prefix = ""): void
  15. {
  16. foreach ($arr as $key => $value) {
  17. $newKey = $prefix ? $prefix . "." . $key : $key;
  18. if (is_array($value)) {
  19. flatten($value, $newKey); // Recursive call for nested arrays
  20. } else {
  21. // Basic validation: Ensure value is not null or empty string
  22. if ($value !== null && $value !== "") {
  23. $flattened[$newKey] = $value;
  24. }
  25. }
  26. }
  27. }
  28. flatten($data);
  29. return $flattened;
  30. }
  31. // Example usage (for testing):
  32. /*
  33. $nestedArray = [
  34. 'name' => 'John Doe',
  35. 'age' => 30,
  36. 'address' => [
  37. 'street' => '123 Main St',
  38. 'city' => 'Anytown',
  39. 'zip' => '12345'
  40. ],
  41. 'hobbies' => ['reading', 'hiking'],
  42. 'null_value' => null,
  43. 'empty_string' => '',
  44. 'nested_array' => [
  45. 'level1' => [
  46. 'level2' => 'value'
  47. ]
  48. ]
  49. ];
  50. $flattenedArray = flattenArray($nestedArray);
  51. print_r($flattenedArray);
  52. */
  53. ?>

Add your comment