Laravel使用内爆存储数组到DB不起作用


Laravel storing array using implode to DB not working

我的代码有一些问题。我无法在 For 语句之外获取变量status值。我试图回应它,但它什么也没做。

这是我的代码:

public function handlequiz()
{
    $datetime = Date("Y-m-d, h:m:s");
    $parameter = DB::table('parameter')->first();
    $countchoice = $parameter->multiplechoice;
    $customer_answer = new CustomerAnswer;
    for ($i=0; $i <= $countchoice; $i++) 
    { 
        $radio = Input::get('radio'.$i);
        $status = DB::table('quiz_answers')->where('answerid', '=', $radio)->lists('status');
    }
    $answerimplode = implode(";", $status); 
    $customer_answer->email = Input::get('email');
    $customer_answer->cust_id = Input::get('id');
    $customer_answer->multiplechoice = $answerimplode;
    $customer_answer->save();
    return Redirect::to('quiz')->with('message', FlashMessage::DisplayAlert('Your answer has been submitted.', 'info'));
}

我试图在里面$status vardump,因为它返回了一个数组,所以我把它内爆了。但在for{}之外,它什么也没返回。

有什么建议可以解决这个问题吗?

你的 for 循环每次迭代都会覆盖 $status 变量。因此,如果上次迭代未找到状态值,则$status变量将是一个空数组,该数组在内爆时会为您提供一个空字符串。

我假设quiz_answers.answerid应该是唯一的,并且您正在尝试为每个无线电选择获取一个状态。如果您的quiz_answers查询应该只返回每条answerid一条记录,则您可能正在寻找pluck()方法,而不是lists()方法。

$status = array();
for ($i=0; $i <= $countchoice; $i++) 
{ 
    $radio = Input::get('radio'.$i);
    // add the 'status' value to the $status array
    // pluck gets the value of the field from the first result, whereas
    // lists would return an array with the value from all the results
    $status[] = DB::table('quiz_answers')->where('answerid', '=', $radio)->pluck('status');
}
// use array_filter to remove any empty values in the $status array
$answerimplode = implode(";", array_filter($status));

作为优化,请使用whereIn函数

radios = array();
for ($i=0; $i <= $countchoice; $i++) 
    $radios[] = Input::get('radio'.$i);
$status = DB::table('quiz_answers')->whereIn('answerid',$radios)->lists('status');
$answerimplode = implode(";", $status);