簡體   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