gpt4 book ai didi

php - 将数据从 CSV 文件插入到现有表中

转载 作者:行者123 更新时间:2023-11-29 20:02:05 35 4
gpt4 key购买 nike

我有一个表,博客,有 3 列。

| id | post_category | post_tags
--------------------------------
| 1 | NULL | example

我有一个 categories.csv 文件,遵循类似的格式:

1, "News"
<小时/>

我想在表中的 id=1 位置插入“新闻”。但是,CSV 文件的长度为+100 行。那么我该如何循环并执行此操作呢?

<小时/>

重要提示:CSV 文件确实有多个对同一 ID 的引用,但具有不同的类别名称。这些需要用“,”分隔

表格(结果)

| id | post_category | post_tags
--------------------------------
| 1 | "News, Shoes" | Shoes

 CSV(文件)

id, post_category
1, "News"
1, "Shoes"

最佳答案

您可以首先解析 CSV 文件并创建一个由 ID 索引的数组,值是与 ID 相对应的类别数组。然后你运行这个数组并执行 SQL 查询(我们只是输出它们)。

$fp = fopen("./file.csv", "r"); # insert path to CSV file here
$categories = [];
$firstLine = TRUE;
while ($line = fgetcsv($fp)) {
if ($firstLine) { # skip first line of CSV file with header
$firstLine = FALSE;
continue;
}
if (count($line) < 2)
continue;
if (!isset($categories($line[0]))
$categories[$line[0]] = [];
$categories[$line[0]][] = $line[1];
}
fclose($fp);
foreach ($categories as $id => $v) {
echo "INSERT INTO `blog`(`id`, `post_category`)
VALUES (".$id.", '".implode(', ', $v)."';<br>";
}

但我建议修改您的数据库布局,这样您就不会在单个列中存储用逗号分隔的多个值。

关于php - 将数据从 CSV 文件插入到现有表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40492107/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com