dtol41388 2016-08-07 00:14
浏览 70
已采纳

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

I have some json data that i am retrieving from an external url. It is not importing correctly unless i take out some of the brackets. Anyone know how to properly import this json data? I don't really need the "success", "num_items", "build time" and "updated at". Im a noobie. Thanks!

Here is the 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);
 }  

Here is 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条回答 默认 最新

  • dtgsl60240 2016-08-07 00:29
    关注

    You were looping through the wrong element of your array. As you want to list the items, your loop must look like :

     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));
    

    I also updated the sql query, for it sends only one request with many values, instead on many requests with one value.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化