<?php
/**
* Flattens a nested array structure with basic input validation.
*
* @param array $data The input array to flatten.
* @return array The flattened array. Returns an empty array on invalid input.
*/
function flattenArray(array $data): array
{
if (!is_array($data)) {
return []; // Handle non-array input.
}
$flattened = [];
function flatten(array $arr, string $prefix = ""): void
{
foreach ($arr as $key => $value) {
$newKey = $prefix ? $prefix . "." . $key : $key;
if (is_array($value)) {
flatten($value, $newKey); // Recursive call for nested arrays
} else {
// Basic validation: Ensure value is not null or empty string
if ($value !== null && $value !== "") {
$flattened[$newKey] = $value;
}
}
}
}
flatten($data);
return $flattened;
}
// Example usage (for testing):
/*
$nestedArray = [
'name' => 'John Doe',
'age' => 30,
'address' => [
'street' => '123 Main St',
'city' => 'Anytown',
'zip' => '12345'
],
'hobbies' => ['reading', 'hiking'],
'null_value' => null,
'empty_string' => '',
'nested_array' => [
'level1' => [
'level2' => 'value'
]
]
];
$flattenedArray = flattenArray($nestedArray);
print_r($flattenedArray);
*/
?>
Add your comment