gpt4 book ai didi

php - 使用PDO将json文件导入MySQL时如何处理标签?

转载 作者:行者123 更新时间:2023-11-29 11:21:12 24 4
gpt4 key购买 nike

我似乎找不到任何引用或示例(或者我没有在正确的位置查找)有关处理标签的信息。更具体地说,使用 PHP/PDO 将标签导入 MySQL。我可以导入所有单值字段,但无法找到如何处理标签,因为每个记录的标签数量各不相同。处理这个问题的最佳方法是什么?

我已经像这样设置了我的数据库......

enter image description here

JSON 数据示例...

{
"name": "Google",
"uri": "https://www.google.com",
"description": "The largest and most popular search engine in the world",
"tags": ["search", "web apps", "adwords"],
},
{
"name": "NFL",
"uri": "https://www.nfl.com",
"description": "The National Football League",
"tags": ["sports", "football"],
},
{
"name": "CNN",
"uri": "https://www.cnn.com",
"description": "Cable News Network",
"tags": [],
},

这是我用来导入单值字段的 PHP/PDO 代码...

$jsondata = file_get_contents('http://www.somewebsite/?format=json');
$data = json_decode($jsondata, true);

$stmt = $db->prepare("insert into bookmark values(?,?,?)");

foreach ($data as $row) {
$stmt->bindParam(1, $row['name']);
$stmt->bindParam(2, $row['uri']);
$stmt->bindParam(3, $row['description']);
$stmt->execute();
}

最佳答案

您的想法是正确的,创建一个标签表,然后创建书签和标签之间的映射。

我要做的是从 json 字符串中爆炸或 json_decode 标签值。遍历数组,检查当前标签是否在标签表中,如果是,则将关系添加到 map 中,如果没有,则插入标签,然后将关系插入到 map 中。

(这样做可以确保标签表中只有一份标签副本。)

关于php - 使用PDO将json文件导入MySQL时如何处理标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38908768/

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