如何解析json并将其保存在数据库中?

时间:2017-11-05 14:53:17

标签: php sql json hierarchical-data

首先抱歉我的英语不好。 我有一个带有json的POST请求,我会将它保存在我的数据库中,该数据库具有邻接List模型。它由2列组成:nameparent_id, 我如何使用PHP解析这个json,然后将其保存在我的数据库中。 有什么建议 ?感谢。

我的json:

{
  "name": "Category 1",

  "children": [
    {
      "name": "Category 1.1",
      "children": [
        {
          "name": "Category 1.1.1",
          "children": [
            {
              "name": "Category 1.1.1.1"
            },
            {
              "name": "Category 1.1.1.2"
            },
            {
              "name": "Category 1.1.1.3"
            }
          ]

        },

        {
          "name": "Category 1.1.2",
          "children": [
            {
              "name": "Category 1.1.2.1"
            },
            {
              "name": "Category 1.1.2.2"
            },
            {
              "name": "Category 1.1.2.3"
            }
          ]
        }
      ]
    },
    {
      "name": "Category 1.2",
      "children": [
        {
          "name": "Category 1.2.1"
        },
        {
          "name": "Category 1.2.2",
          "children": [
            {
              "name": "Category 1.2.2.1"
            },
            {
              "name": "Category 1.2.2.2"
            }
          ]
        }
      ]
    }
  ]
}

3 个答案:

答案 0 :(得分:1)

首先我们将使用json_decode解码json,之后我们将其插入数据库,我希望这会对你有所帮助

       <?php

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

        $array_data = $data['children'];

     //your database connection here
     $servername = "hostname";
    $username = "user";
    $password = "password";
    $dbname = "database";

   // 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 mytable (name, ParentID) VALUES ('" . $row["name"] . "', '" . $row["ParentId"] . "')";
   $conn->query($sql);
 }
  $conn->close();
    ?>

答案 1 :(得分:0)

要解析JSON,请尝试使用PHP的json_decode函数。 http://php.net/manual/en/function.json-decode.php

我不能告诉你如何在不知道它是什么类型的数据库的情况下将它存储在数据库中,但你可能应该使用PHP的PDO(PHP数据对象)API。 (http://php.net/manual/en/book.pdo.php)它允许您准备和执行查询/插入/命令,就像数据库的shell一样。

答案 2 :(得分:0)

<?php
/*
     Database query:  CREATE TABLE `stdtable` (

std_id int(11)NOT NULL,   std_name varchar(255)NOT NULL,   std_age varchar(255)NOT NULL,   std_gender varchar(255)NOT NULL,   std_num varchar(255)NOT NULL,   std_street varchar(255)NOT NULL,   std_city varchar(255)NOT NULL,   std_country varchar(255)NOT NULL,   std_postal varchar(255)NOT NULL,   std_dept varchar(255)NOT NULL,   std_semstr varchar(255)NOT NULL,   std_major varchar(255)NOT NULL )ENGINE = InnoDB DEFAULT CHARSET = utf8;

*/
/* //JSON Data
   {
"stdID": "0106",
"stdData":{
    "stdName":"Mirwaise",
    "stdAge":"23",
    "stdGender":"Male",
    "stdNo":"12345",
    "stdAddress":{
        "stdStreet":"786 Street",
        "stdCity":"Riyadh",
        "stdCountry":"Saudi Arabia",
        "stdPostal":"98765"
    }
},
"stdEdu":{
    "stdDept":"Computer Science",
    "stdSemester":"8",
    "stdMajor":"Web Programming"
}

}

 */
//connect and select the database
$connect = new mysqli('localhost', 'root', 'cdn123', 'jsondb');

// get the contents of the JSON file 
$jsonCont = file_get_contents('studJson.json');

//decode JSON data to PHP array
$content = json_decode($jsonCont, true);

 //Fetch the details of Student
 $std_id = $content['stdID'];
 $std_name = $content['stdData']['stdName'];
 $std_age = $content['stdData']['stdAge'];
 $std_gender = $content['stdData']['stdGender'];
 $std_no = $content['stdData']['stdNo'];
 $std_street = $content['stdData']['stdAddress']['stdStreet'];
 $std_city = $content['stdData']['stdAddress']['stdCity'];
 $std_country = $content['stdData']['stdAddress']['stdCountry'];
 $std_postal = $content['stdData']['stdAddress']['stdPostal'];
 $std_dept = $content['stdEdu']['stdDept'];
 $std_sem = $content['stdEdu']['stdSemester'];
 $std_major = $content['stdEdu']['stdMajor'];

echo date('Y-m-d h:i:s')."<br/>";

$valueStrings = '';
for($i=0; $i<10; $i++){
    $valueStrings .= "('".$std_name."', '".$std_age."', '".$std_gender."', '".$std_no."', '".$std_street."', '".$std_city."', '".$std_country."', '".$std_postal."', '".$std_dept."', '".$std_sem."', '".$std_major."'),";
}

$valueStrings2 = rtrim($valueStrings, ',');

//Insert the fetched Data into Database
$query = "INSERT INTO stdtable (std_name, std_age, std_gender, std_num, std_street, std_city, std_country, std_postal, std_dept, std_semstr, std_major)
VALUES ".$valueStrings2;

$result = $connect->query($query) or die("Cannot write");   

if($result) {
    echo "Records added successfully.";
} else{
    echo "ERROR: Could not able to execute";
}

echo date('Y-m-d h:i:s')."<br/>";

&GT;