How can recursion be implemented in PHP to create nested arrays from multi-dimensional data?

To implement recursion in PHP to create nested arrays from multi-dimensional data, you can create a function that iterates over the data and checks if each element is an array. If it is, the function can call itself recursively to create nested arrays. This approach allows you to handle data of varying depths and create a nested array structure accordingly.

function createNestedArray($data) {
    $result = [];
    
    foreach ($data as $key => $value) {
        if (is_array($value)) {
            $result[$key] = createNestedArray($value);
        } else {
            $result[$key] = $value;
        }
    }
    
    return $result;
}

// Example multi-dimensional data
$data = [
    'key1' => 'value1',
    'key2' => [
        'key3' => 'value3',
        'key4' => [
            'key5' => 'value5'
        ]
    ]
];

$nestedArray = createNestedArray($data);

print_r($nestedArray);