PHP

Flatten Nested Associative Arrays into a Single-Level Array

Learn to convert a complex multi-dimensional associative array into a flat, single-level array, handling nested structures gracefully while merging keys.

function flattenArray(array $array, string $prefix = ''): array {
    $result = [];
    foreach ($array as $key => $value) {
        $newKey = $prefix === '' ? $key : $prefix . '_' . $key;
        if (is_array($value) && !empty($value)) {
            $result = array_merge($result, flattenArray($value, $newKey));
        } else {
            $result[$newKey] = $value;
        }
    }
    return $result;
}

$nestedArray = [
    'user_id' => 123,
    'profile' => [
        'first_name' => 'John',
        'last_name' => 'Doe',
        'contact' => [
            'email' => '[email protected]',
            'phone' => '123-456-7890'
        ]
    ],
    'status' => 'active'
];

$flatArray = flattenArray($nestedArray);
print_r($flatArray);
How it works: The `flattenArray` function recursively traverses a multi-dimensional associative array. For each nested array it encounters, it constructs new keys by prepending the parent key (e.g., `profile_first_name`). Scalar values are directly added to the `$result` array using these new keys. The `array_merge` function combines the results from recursive calls, building a single, flat associative array from the complex nested structure.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs