如何在Laravel中存储JSON多数组数据数据库?

时间:2018-09-10 07:21:30

标签: php sql laravel

完成完整的考试后,我在在线考试门户上工作,我希望将结果用户详细信息存储在数据库中,所有数据均来自API。

数据外观

{
"user_id": "420",
"test_id": "2",
"question_id": [
    "12",
    "13"
],
"c_ans": [
    "a",
    "b"
],
"ans": [
    "a",
    "b"
]

}

我的Question_id数组数据存储成功,但c_ans和数组未成功存储。

我的控制器

   $fbres       = new Testapp;
    $json        = $request->all();
    $data        = $json;

    $finalData = array();
    $blankArr = array();
    //Check for array 1-d or 2-d
    if(isset($data["user_id"])){
      array_push($blankArr, $data);
    }else{
     $blankArr = $data;
    } 

    foreach ($blankArr as $key => $value)
    {

        $usr_id     = $value['user_id']['0'];
        $test_id    = $value['test_id']['0'];
        $c_ans      = $value['c_ans']['0'];
        $ans        = $value['ans']['0'];



        foreach($value['question_id'] as $k => $v){
             $finalData = array('user_id'=> $usr_id, 'question_id'=> $v, 'test_id'=> $test_id,'c_ans' => $c_ans,'ans'=>$ans);
              $store= $fbres::insert($finalData);
        } 
    }

    if($store)
  {
    return response([
                'Success' => "1",
                'Message' => "Result Submitted Successfull..."
            ]);   
  }

已存储答案 this is issue

1 个答案:

答案 0 :(得分:1)

您可以根据自己的数据执行以下操作:

$fbres       = new Testapp;
    $json        = $request->all();
    $data        = $json;

    $finalData = array();
    $blankArr = array();
    //Check for array 1-d or 2-d
    if(isset($data["user_id"])){
      array_push($blankArr, $data);
    }else{
     $blankArr = $data;
    } 

    foreach ($blankArr as $key => $value)
    {

        $usr_id     = $value['user_id'];
        $test_id    = $value['test_id'];




        foreach($value['question_id'] as $k => $v){
             $c_ans      = $value['c_ans'][$k];
             $ans        = $value['ans'][$k];
             $finalData = array('user_id'=> $usr_id, 'question_id'=> $v, 'test_id'=> $test_id,'c_ans' => $c_ans,'ans'=>$ans);
              $store= $fbres::insert($finalData);
        } 
    }

    if($store)
  {
    return response([
                'Success' => "1",
                'Message' => "Result Submitted Successfull..."
            ]);   
  }

问题是$ c_ans,$ ans和quest_id具有一对一的映射。因此,也可以一一检索价值。

希望这会对您有所帮助。