How can recursion be used effectively in PHP to handle multidimensional arrays for database operations?

When dealing with multidimensional arrays in PHP for database operations, recursion can be used effectively to traverse through the nested arrays and perform the necessary database operations on each element. By using a recursive function, you can easily handle arrays of any depth without the need for complex loops or manual iteration.

function handleMultidimensionalArray($array, $pdo) {
    foreach ($array as $key => $value) {
        if (is_array($value)) {
            handleMultidimensionalArray($value, $pdo);
        } else {
            // Perform database operation here using $value
            $stmt = $pdo->prepare("INSERT INTO table_name (column_name) VALUES (:value)");
            $stmt->bindParam(':value', $value);
            $stmt->execute();
        }
    }
}

// Example of how to use the function
$pdo = new PDO("mysql:host=localhost;dbname=database_name", "username", "password");
$array = [
    "key1" => "value1",
    "key2" => [
        "subkey1" => "subvalue1",
        "subkey2" => "subvalue2"
    ]
];

handleMultidimensionalArray($array, $pdo);