解码Json数据数组并插入到mysql中 [英] Decode Json data Array and insert in to mysql

查看:228
本文介绍了解码Json数据数组并插入到mysql中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里可能已经问过这个问题,但是我尝试搜索找不到它 我有如下的Json数据

This question already may asked here but i tried search couldn't find it I have Json data like below

{"CityInfo":[{"CityCode":"5599","Name":"DRUSKININKAI"},{"CityCode":"2003","Name":"KAUNAS"},{"CityCode":"2573","Name":"KLAIPEDA"},{"CityCode":"1692","Name":"VILNIUS"}],"StartTime":"2016-11-05 07:20:34","EndTime":"2016-11-05 07:20:34"}

我尝试使用php提取这些内容并插入到mysql db中.但是它对我不起作用,因为我是编码初学者,请帮助解决此问题

i tried to extract these using php and inserted to mysql db. but its not work for me as i beginner in coding please help to solve this

下面我尝试过

$jsondata = file_get_contents($jsonFile);
$data = json_decode($jsondata, true);
echo $data['Name'];
echo $data['CityCode'];
$db->save($data, "tableName"); // i found a php app to insert json to db

推荐答案

您的php代码中存在一些问题.代码$data = json_decode($jsondata, true);确实将您的json数据转换为PHP数组.但是,如果您需要提取需要插入表中的数据,则需要这样做

There are some problems in your php code. The code $data = json_decode($jsondata, true); indeed convert your json data into PHP array. But if you need to extract the datas that you need to insert into your table, then you need to do like

$array_data = $data['CityInfo'];

现在,此$array_data包含需要插入表中的数据数组.您可以继续

Now this $array_data contains the array of data that needs to be inserted into your tables.You can continue with

$db->save($array_data, "tableName");

或者您可以使用PHP MySQLiforEach循环(如

or you could manually insert each row using a PHP MySQLi and forEach loop like

$conn = new mysqli($servername, $username, $password, $dbname);

foreach ($array_data as $row) {
    $sql = "INSERT INTO cityinfo (CityCode, Name) VALUES ('" . $row["CityCode"] . "', '" . $row["Name"] . "')";
    $conn->query($sql);
}

完整示例

<?php

$jsonFile="CityInfo.json";
$jsondata = file_get_contents($jsonFile);
$data = json_decode($jsondata, true);

$array_data = $data['CityInfo'];

$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "yourDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

foreach ($array_data as $row) {
    $sql = "INSERT INTO cityinfo (CityCode, Name) VALUES ('" . $row["CityCode"] . "', '" . $row["Name"] . "')";
    $conn->query($sql);
}

$conn->close();
?>

这篇关于解码Json数据数组并插入到mysql中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆