简体   繁体   English

使用PHP将JSON中的多个数组数据插入MySQL

[英]Insert JSON in multiple array data to MySQL using PHP

I want to insert my JSON data to MySQL DB using PHP... 我想使用PHP将JSON数据插入MySQL数据库...

This is my JSON data called "data.json" 这是我的JSON数据,称为“ data.json”

{
"allRoundData": [{
    "name": "Animals",
    "timeLimitInSeconds": 20,
    "pointsAddedForCorrectAnswer": 10,
    "questions": [{
        "questionText": "Lions are carnivores: true or false?",
        "answers": [{
            "answerText": "True",
            "isCorrect": true
        }, {
            "answerText": "False",
            "isCorrect": false
        }]
    }, {
        "questionText": "What do frogs eat?",
        "answers": [{
            "answerText": "Pizza",
            "isCorrect": false
        }, {
            "answerText": "Flies",
            "isCorrect": true
        }]
    }, {
        "questionText": "Where do mice live?",
        "answers": [{
            "answerText": "In the sea",
            "isCorrect": false
        }, {
            "answerText": "On the moon",
            "isCorrect": false
        }, {
            "answerText": "On land",
            "isCorrect": true
        }, {
            "answerText": "In a tree",
            "isCorrect": false
        }]
    }]
}]

} }

This is my PHP script 这是我的PHP脚本

<?php

include 'bl_Common.php';

$con = dbConnect();

 // use prepare statement for insert query
$st = mysqli_prepare($con, 'INSERT INTO data (round_name, time_limit, points_added, question_text, answer_text, isCorrect) VALUES (?, ?, ?, ?, ?, ?)');

// bind variables to insert query params
mysqli_stmt_bind_param($st, 'siisss', $name, $time, $points, $question, $answer, $isCorrect);

// read json file
$filename = 'data.json';
$json = file_get_contents($filename);   

echo $json;

//convert json object to php associative array
$data = json_decode($json, true);

// loop through the array
foreach ($data as $row) {

    // get the employee details
    $name = $row["allRoundData"]["name"];
    $time = $row['allRoundData']['timeLimitInSeconds'];
    $points = $row['allRoundData']['pointsAddedForCorrectAnswer'];
    $question = $row['allRoundData']['questions']['questionText'];
    $answer = $row['allRoundData']['answers']['answerText'];
    $isCorrect = $row['allRoundData']['answers']['isCorrect'];

    // execute insert query
    mysqli_stmt_execute($st);
}

//close connection
mysqli_close($con);

?> ?>

I found an error that say "Notice: Undefined index: allRoundData in ..." But it's appearing there. 我发现一个错误,提示“注意:未定义的索引:...中的allRoundData”,但它在那里出现。

You need to use nested loop for getting all the values like this and try to understand the use of foreach . 您需要使用嵌套循环来获取所有类似的值,并尝试了解foreach的用法。 foreach is used to loop through the array to get the value until N'th values . foreach用于遍历数组以获取直到第N个值的值。

Foreach reference Foreach参考

    foreach ($array["allRoundData"] as $row) 
    {

        $name = $row["name"];
        $time = $row['timeLimitInSeconds'];
        $points = $row['pointsAddedForCorrectAnswer'];

       foreach($row['questions'] as $row1)
       {    
            $question= $row1['questionText'];

            foreach($row1['answers'] as $row2)
            {

                $answer = $row2['answerText'];

                $isCorrect= $row2['isCorrect'];

                echo "INSERT INTO data (round_name, time_limit, points_added, question_text, answer_text, isCorrect) VALUES ('". $name."',".$time.",".$points.",'". $question."','". $answer ."','".  $isCorrect."') </br>";  
            }

       }


    }

OUTPUT : 输出:

INSERT INTO data (round_name, time_limit, points_added, question_text, answer_text, isCorrect) VALUES ('Animals',20,10,'Lions are carnivores: true or false?','True','1') 

INSERT INTO data (round_name, time_limit, points_added, question_text, answer_text, isCorrect) VALUES ('Animals',20,10,'Lions are carnivores: true or false?','False','') 

 INSERT INTO data (round_name, time_limit, points_added, question_text, answer_text, isCorrect) VALUES ('Animals',20,10,'What do frogs eat?','Pizza','') 

 INSERT INTO data (round_name, time_limit, points_added, question_text, answer_text, isCorrect) VALUES ('Animals',20,10,'What do frogs eat?','Flies','1') 

 INSERT INTO data (round_name, time_limit, points_added, question_text, answer_text, isCorrect) VALUES ('Animals',20,10,'Where do mice live?','In the sea','') 

INSERT INTO data (round_name, time_limit, points_added, question_text, answer_text, isCorrect) VALUES ('Animals',20,10,'Where do mice live?','On the moon','') 

 INSERT INTO data (round_name, time_limit, points_added, question_text, answer_text, isCorrect) VALUES ('Animals',20,10,'Where do mice live?','On land','1') 

INSERT INTO data (round_name, time_limit, points_added, question_text, answer_text, isCorrect) VALUES ('Animals',20,10,'Where do mice live?','In a tree','') 

Your loop is going wrong, you need to loop data inside the allRoundData . 您的循环出错了,您需要在allRoundData内部循环数据。 So, please try this code 所以,请尝试这段代码

foreach ($data["allRoundData"] as $row) {

    // get the employee details
    $name = $row["name"];
    $time = $row['timeLimitInSeconds'];
    $points = $row['pointsAddedForCorrectAnswer'];
    $question = $row['questions']['questionText'];//wrong code
    $answer = $row['answers']['answerText'];//wrong code
    $isCorrect = $row['answers']['isCorrect'];//wrong code

    // execute insert query
    mysqli_stmt_execute($st);
}

the comment //wrong code i have written because those are arrays, and you can't directly access without index you should use $row['answers'][$index]['answerText'] where $index is from 0 to count($row['answers'])-1 注释//wrong code//wrong code因为它们是数组,因此如果没有索引就不能直接访问,应该使用$row['answers'][$index]['answerText'] ,其中$index from 0 to count($row['answers'])-1

If you need static results then use specific index, otherwise you need to loop those variables to get your desired result 如果需要静态结果,请使用特定的索引,否则需要循环这些变量以获得所需的结果

You've got lost in the complexity of the JSON data: 您已经迷失了JSON数据的复杂性:

  • Your JSON represents an array with one key: $data['allRoundData'] . 您的JSON用一个键表示一个数组: $data['allRoundData']
  • In turn, it has one element $data['allRoundData'][0] 反过来,它具有一个元素$data['allRoundData'][0]
  • In that array, you have $data['allRoundData'][name] , $data['allRoundData'][timeLimitInSeconds] , $data['allRoundData'][pointsAddedForCorrectAnswer] 在该数组中,您有$data['allRoundData'][name]$data['allRoundData'][timeLimitInSeconds]$data['allRoundData'][pointsAddedForCorrectAnswer]
  • After that you have another array: $data['allRoundData'][questions] 之后,您还有另一个数组: $data['allRoundData'][questions]

You should get the preliminary data directly from $data['allRoundData'][0] , and then get the actual questions using: 您应该直接从$data['allRoundData'][0]获取初步数据,然后使用以下方法获取实际问题:

foreach($data['allRoundData'][0][questions] as $question) {}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM