我有multidimentions数组hrefs:
Array
(
[1] => Array
(
[0] => http://213b572-ba681bf9cc9e
[1] => http://f057-4139-ac40-bc4449722ffc
[2] => http://b-c151-4ba1-b7b7-842771c36d6b
[3] => http://5a77fb-8fce-4793-868f-c9fd73524037
)
[2] => Array
(
[0] => http://8-d832-4b34-a55b-da04ad8cdd09
[1] => http://b38-6a60-4233-b207-f40fae2ef431
[2] => http://3-f31c-49c4-87ee-fcada05a105f
[3] => http://07514-e438-45e2-906e-b440cbcbf8dc
)
......
[76] => Array
(
[0] => http://8-d832-4b34-a55b-da04ad8cdd09
[1] => http://b38-6a60-4233-b207-f40fae2ef431
[2] => http://3-f31c-49c4-87ee-fcada05a105f
[3] => http://07514-e438-45e2-906e-b440cbcbf8dc
)
当我将数组hrefs插入数据库
时foreach ($hrefs as $id_page => $href) {
foreach ($href as $value) {
mysqli_query($con, "INSERT INTO urls(`id`, `id_page`, `url`)
VALUES ('', '$id_page', '$value')");
}
}
mysqli_close($con);
我希望我的数据库是:
| id | id_page | url |
| 1 | 1 | http://jjjjjjjjj |
| 2 | 1 | http://jjjjjjjjj|
| 3 | 1 | http://jjjjjjjjj|
......
| 1000 | 76 | http://jjjjjjjjj|
但结果:
| id | id_page | url |
| 1 | 1 | http://jjjjjjjjj |
| 2 | 1 | http://jjjjjjjjj|
| 3 | 1 | http://jjjjjjjjj|
......
| 500 | 35 | http://jjjjjjjjj|
| 501 | 1 | http://jjjjjjjjj|
当插入id_page循环到35并返回开始1时。 $ hrefs是上面的multidimentions数组。有什么决心?
答案 0 :(得分:1)
我会这样试试:
foreach ($hrefs as $id_page => $href) {
foreach ($href as $value) {
mysqli_query($con, "INSERT INTO urls(`id_page`, `url`)
VALUES ('".$id_page."', '".$value."')");
}
}
mysqli_close($con);
假设" id"在表格中设置为auto_increment。
编辑1:检查"网址"中的数据类型table:也许是你的" id_page"太小,不能容纳大价值。例如,将其设置为int(11)。
Edit2:如果存在任何性能问题,您应该只执行一个具有多个值的查询,例如:
$sql = 'INSERT INTO urls(`id_page`, `url`) VALUES ';
foreach ($hrefs as $id_page => $href) {
foreach ($href as $value) {
$sql .= "('".$id_page."','".$value."'),";
}
}
$sql = substr($sql, 0, -1); // delete last comma
mysqli_query($con, $sql);
mysqli_close($con);