以下是一种可能的方法,用于将PHP数组中的半数以上组合写入数据库:
count()
函数获取数组的长度,并使用ceil()
函数将长度除以2并向上取整,以确定半数以上的数量。$array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
$length = count($array);
$half = ceil($length / 2);
array_chunk()
函数将数组分成大小为半数以上的子数组。该函数接受两个参数:要分割的数组和每个子数组的长度。将半数以上的数量作为第二个参数传递给array_chunk()
函数。$chunks = array_chunk($array, $half);
$dsn = 'mysql:host=localhost;dbname=test';
$username = 'username';
$password = 'password';
$db = new PDO($dsn, $username, $password);
foreach ($chunks as $chunk) {
$placeholders = implode(',', array_fill(0, $half, '?'));
$stmt = $db->prepare("INSERT INTO table_name (column1, column2) VALUES ($placeholders)");
$stmt->execute($chunk);
}
在上面的示例中,我们使用implode()
函数将占位符连接起来,以构建插入语句中的占位符。然后,我们使用prepare()
函数准备插入语句,并使用execute()
函数将子数组中的值传递给占位符。
请注意,上述示例假设数据库连接的详细信息已正确设置,并且表名和列名已正确设置。您需要根据自己的实际情况进行适当的更改。
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站