gpt4 book ai didi

php - 将 JSON 插入 MySQL。

转载 作者:太空宇宙 更新时间:2023-11-03 12:12:51 25 4
gpt4 key购买 nike

我有 .json 文件 [categories.json]

像这样

{
"apple": [
"fruit",
"15"
],
"cat": [
"animal",
"400"
],
"pumpkin": [
"vegetables",
"20"
],
"orange": [
"fruit",
"30"
]
}

我想像这样使用循环 php 将 json 对象插入到 mysql

|___id__|___ product__|_____type_____|__price__|
| 1 | apple | fruit | 15 |
| 2 | cat | animal | 400 |
| 3 | pumpkin | vegetables | 20 |
| 4 | orange | fruit | 30 |

我该怎么做谢谢

最佳答案

 $file = 'www.mysite.com/categories.json';
$data = json_decode(file_get_contents($file), true);

foreach($data as $product => $row){
$sql = "INSERT INTO product ";
$sql .= "SET product='".mysql_real_escape_string($product)."',type='".mysql_real_escape_string($row[0])."',price=".mysql_real_escape_string($row[1]);
mysql_query($sql);
} // hoping your id field in db is auto_increment

关于php - 将 JSON 插入 MySQL。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23492110/

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