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

时间:2017-03-28 03:58:34

标签: php mysql json

我想使用PHP将我的JSON数据插入MySQL数据库......

这是我的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
        }]
    }]
}]

}

这是我的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);

&GT;

我发现了一条错误,上面写着“注意:未定义索引:allRoundData in ...” 但它出现在那里。

3 个答案:

答案 0 :(得分:1)

你需要使用嵌套循环来获取这样的所有值,并尝试理解foreach的使用。 foreach用于遍历数组以获取值,直到N'为止值。

Foreach reference

    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>";  
            }

       }


    }

输出:

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','') 

答案 1 :(得分:0)

您的循环出错了,您需要在allRoundData内循环数据。所以,请尝试此代码

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);
}

我写的评论//wrong code因为这些是数组,你不能在没有索引的情况下直接访问,你应该$row['answers'][$index]['answerText']使用$index from 0 to count($row['answers'])-1

如果您需要静态结果,则使用特定索引,否则您需要循环这些变量以获得所需结果

答案 2 :(得分:0)

你迷失在JSON数据的复杂性中:

  • 您的JSON代表一个包含一个键的数组:$data['allRoundData']
  • 反过来,它有一个元素$data['allRoundData'][0]
  • 在该数组中,您有$data['allRoundData'][name]$data['allRoundData'][timeLimitInSeconds]$data['allRoundData'][pointsAddedForCorrectAnswer]
  • 之后你有另一个数组:$data['allRoundData'][questions]

您应该直接从$data['allRoundData'][0]获取初步数据,然后使用以下方式获取实际问题:

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