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

首先抱歉我的英文不好。
我有一个带有json的POST请求,我会把它保存在我的 具有邻接List模型的数据库。 它由2列组成: name </ code>和 parent_id </ code>,
如何使用php解析此json,然后将其保存在我的数据库中。

任何建议? 谢谢。</ p>

我的json:</ p>

  {
“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”
}
]

},

{
“名称”:“类别1.1.2”,
“儿童”:[
{
“名称”:“类别1.1.2.1”

},
{
“名称”:“类别1.1.2.2”
},
{
“名称”:“类别1.1.2.3”
}
]
}
}
]

},
{
“名称”:“类别1.2”,
“儿童”:[
{
“名称”:“类别1.2.1”
},
{
“ 名称“:”类别1.2.2“,
”“儿童”:[
{
“name”:“Category 1.2.2.1”
},
{
“name”:“Category 1.2.2.2”
}
]
}
]
}
}

]

}
</ code> </ pre>
</ div>

展开原文

原文

first sorry for my bad english. I have a POST request with a json inside and i would save it in my database which has adjacency List model . It composed with 2 columns: name and parent_id, How can i parse this json using php, then save it in my database. Any suggestions ? Thanks.

My 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"
            }
          ]
        }
      ]
    }
  ]
}

dongsou8980
dongsou8980 你可以在这里放一些代码片段
2 年多之前 回复

3个回答



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

 &lt;?php 

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

$ array_data = $ data ['children'];

//这里你的数据库连接
$ servername =“hostname”;
$ username =“user”;
$ password =“password “;
$ dbname =”database“;

//创建连接
$ conn = new mysqli($ servername,$ username,$ password,$ dbname);
//检查连接
如果( $ conn-&gt; connect_error){
die(“连接失败:”。$ conn-&gt; connect_error);
}
foreach($ array_data as $ row){
$ sql =“INSERT INTO mytable( name,ParentID)VALUES('“。$ row [”name“]。”','“。$ row [”ParentId“]。”')“;
$ conn-&gt; query($ sql); \ n}
$ conn-&gt; close();
?&gt;
</ code> </ pre>
</ div>

展开原文

原文

First we will decode the json using json_decode, after we will insert that to database, i hope this will help you

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



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

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

展开原文

原文

To parse the JSON, try using PHP's json_decode function. http://php.net/manual/en/function.json-decode.php

I can't give you specifics on how to store it in the database without knowing what type of database it is, but you probably should use PHP's PDO (PHP Data Object) API. (http://php.net/manual/en/book.pdo.php) It lets you prepare and execute queries/insertions/commands just like you can the database's shell.

<?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/>";

?>

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问