将数组键增加一,以提供更多功能

时间:2016-02-26 06:02:13

标签: php mysql

  

我想将$quiz_option增加1,如$quiz_option1,$quiz_option2,$quiz_option3

这里我提供了更多功能来将答案插入数据库。 通过使用上面的选项字段我不知道怎么可能。我正在使用最后一个插入ID来执行以下任务。

$Quiz_ID = $quiz->insert();

for($i=0;$i<count($_REQUEST['quiz_options']);$i++)
{                           
    $data=array
    (
        "quiz_Id"=>$Quiz_ID,
        "quiz_Options1"=>$_REQUEST['quiz_options'][$i]
        //To change in above line of code like quiz_Options1, quiz_Options2
    );
    $quiz->insertOptions($data,'quizoptions');
}

3 个答案:

答案 0 :(得分:2)

我认为这就是你所需要的:

$Quiz_ID = $quiz->insert();

$data = array(
    "quiz_Id" => $Quiz_ID;
)

for($i=0; $i<count($_REQUEST['quiz_options']); $i++) {
    $key = "quiz_Options" . ($i+1);
    $data[$key] = $_REQUEST['quiz_options'][$i];
}

$quiz->insertOptions($data,'quizoptions');

$ data(print_r($ data))的示例如下所示:

Array
(
    [quiz_Id] => 111
    [quiz_Options1] => aaa
    [quiz_Options2] => bbb
    [quiz_Options3] => ccc
)

答案 1 :(得分:1)

应该是这样的:

for($i=0;$i<count($_REQUEST['quiz_options']);$i++)
{                           
    $data=array
    (
        "quiz_Id"=>$Quiz_ID,
        "quiz_Options".$i =>$_REQUEST['quiz_options'][$i]
        //To change in above line of code like quiz_Options1, quiz_Options2
    );
    $quiz->insertOptions($data,'quizoptions');
}

答案 2 :(得分:0)

你需要在数组开始之前将一个预先增加到$i ..

for($i=0;$i<count($_REQUEST['quiz_options']);$i++)
{
$key = $i;
$data=array
(
    "quiz_Id"=>$Quiz_ID,
    "quiz_Options".++$key =>$_REQUEST['quiz_options'][$i]
    //To change in above line of code like quiz_Options1, quiz_Options2
);
$quiz->insertOptions($data,'quizoptions');
}