当用户获得考试时,我正在laravel上的在线考试系统上工作,我想从API接收一些数据并存储在数据库中。 数据将是这样的。
{
"user_id": [
"420"
],
"test_id": [
"12"
],
"question_id": [
"1",
"2",
"3",
"4"
]
}
我的控制器
$fbres = new Testapp;
$json = $request->all();
$data = $json;
$user_id = $request->user_id;
$question_id = $request->question_id;
$test_id = $request->test_id;
foreach ($data as $key)
{
$user_id = $key['user_id'];
$test_id = $key['test_id'];
$question_id = $key['question_id'];
$data1 = array(
array('user_id'=> $user_id, 'question_id'=> $question_id, 'test_id'=> $test_id)
);
$fbres::insert($data1);
}
答案 0 :(得分:1)
使用json_encode()
php方法对数组进行编码。无需调用insert into循环。这很耗时,可能会使数据库崩溃。
$fbres = new Testapp;
$json = $request->all();
$data = $json;
$data = $request->ques;
$user_id = $request->user_id;
$question_id = $request->question_id;
$test_id = $request->test_id;
$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'];
foreach($value['question_id'] as $k => $v){
$finalData = array('user_id'=> $usr_id, 'question_id'=> $v, 'test_id'=> $test_id);
$fbres::insert($finalData);
}
}
希望它会对您有所帮助。
答案 1 :(得分:0)
使用json_encode函数将数组转换为json字符串,然后将其存储
Document.SelectionChanged event