【问题标题】:Insert parsed json data into MySQL table将解析后的 json 数据插入 MySQL 表中
【发布时间】:2019-01-24 05:16:46
【问题描述】:

我已经解析了多维数组。我需要做的最后一件事:将数据插入 mysql 表,另一件事我想知道如何将多维数组实际插入表中,我应该使用第二个 $sql 查询和另一个表吗? 下面只是示例,我只使用了三个变量“id、main、icon”,当然需要将它们全部打包。感谢您的帮助。谢谢

 $jsonIterator = new RecursiveIteratorIterator(
  new RecursiveArrayIterator(json_decode($data, TRUE)),
  RecursiveIteratorIterator::SELF_FIRST);
  foreach($jsonIterator as $key=>$value)
   { 
   $query = "INSERT INTO json1 (id, main, icon) VALUES (
     '".$key["coord"]."', 
     '".$key["lon"]."', 
     '".$key["lat"]."'); "; 
   if(is_array($value))
     { echo "$key:\n"; }
   else
     { echo "$key => $value\n"; } 
}

这是我的 json 文件

{
    "coord": {
        "lon": 22,
        "lat": 50.04
    },
    "weather": [{
        "id": 804,
        "main": "Clouds",
        "description": "overcast clouds",
        "icon": "04n"
    }],
    "base": "stations",
    "main": {
        "temp": 267.15,
        "pressure": 1007,
        "humidity": 79,
        "temp_min": 267.15,
        "temp_max": 267.15
    },
    "visibility": 10000,
    "wind": {
        "speed": 4.6,
        "deg": 50
    },
    "clouds": {
        "all": 90
    },
    "dt": 1548271800,
    "sys": {
        "type": 1,
        "id": 1711,
        "message": 0.0097,
        "country": "UK",
        "sunrise": 1548224204,
        "sunset": 1548256302
    },
    "id": 759734,
    "name": "London",
    "cod": 200
}

【问题讨论】:

    标签: php mysql json


    【解决方案1】:

    您似乎让这件事变得比需要的困难得多。该 JSON 文件中没有数组,它只是一个对象,所以没有什么可以迭代的。您也不需要递归迭代器。

    $array = json_decode($data, true);
    $id = $array['id'];
    $lon = $array['coord']['lon'];
    $lat = $array['coord']['lat'];
    $query = "INSERT INTO json1 (id, main, icon) VALUES ($id, $lon, $lat)";
    

    【讨论】:

      猜你喜欢
      • 2015-01-23
      • 1970-01-01
      • 1970-01-01
      • 2015-01-09
      • 1970-01-01
      • 2010-11-03
      • 2013-02-10
      • 2019-09-12
      • 2020-04-03
      相关资源
      最近更新 更多