繁体   English   中英

将JSON插入MySQL。

[英]Insert JSON into MySQL.

我有.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

只需使用json_decode将您的Json文件转换为数组,然后循环并插入即可,就像使用数组那样

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM