PHP将嵌套的json保存到mysql数据库

时间:2016-08-07 00:14:33

标签: php mysql json

我有一些我从外部网址检索的json数据。除非我取出一些括号,否则它无法正确导入。有谁知道如何正确导入这个json数据?我真的不需要"成功"," num_items","构建时间"和"在"更新。我是一个noobie。谢谢!

这是php

$filename = "http://www.someurl.com/data.json";
$data = file_get_contents($filename);  
$array = json_decode($data, true);

 foreach($array as $row)  
 {  
      $sql = "INSERT INTO table_all_items(name, quality) VALUES (
      '".$row["name"]."', 
      '".$row["quality"]."'
      )";       
mysqli_query($connect, $sql);
 }  

这是data.json

{
    "success": true,
    "num_items": 7312,
    "items": [
        {
            "name": "Net",
            "quality": "New"
        },
        {
            "name": "Ball",
            "quality": "New"
        },
        {
            "name": "Hoop",
            "quality": "Used"
        }
    ],
    "build_time": 320,
    "updated_at": 15680
}

1 个答案:

答案 0 :(得分:0)

您正在循环遍历数组的错误元素。 如果要列出项目,则循环必须如下所示:

 foreach($array["items"] as $row)  


//$filename = "http://www.someurl.com/data.json";
//$data = file_get_contents($filename);  
$data='{
    "success": true,
    "num_items": 7312,
    "items": [
        {
            "name": "Net",
            "quality": "New"
        },
        {
            "name": "Ball",
            "quality": "New"
        },
        {
            "name": "Hoop",
            "quality": "Used"
        }
    ],
    "build_time": 320,
    "updated_at": 15680
}';
$array = json_decode($data, true);
$sql = "INSERT INTO table_all_items(name, quality) VALUES ";
 foreach($array["items"] as $row)  
 {  
      $sql = $sql." (
      '".$row["name"]."', 
      '".$row["quality"]."'
      ),";       
 }  
  mysqli_query($connect, substr($sql,0,-1));

我还更新了sql查询,因为它只发送一个包含许多值的请求,而是发送了许多具有一个值的请求。