使用for循环生成数组

时间:2017-07-22 08:54:44

标签: php arrays codeigniter

我正在使用CodeIgniter框架并从html表单中获取值。

目前我正在准备具有固定输入数量的数组,ques_X是输入,但是当ques_x数字增加时,我需要手动添加每个密钥对值,如ques_11,ques_12 ......

$answers = array(
                'ques_1'    =>  $this->input->post('ques_1', TRUE),
                'ques_2'    =>  $this->input->post('ques_2', TRUE),
                'ques_3'    =>  $this->input->post('ques_3', TRUE),
                'ques_4'    =>  $this->input->post('ques_4', TRUE),
                'ques_5'    =>  $this->input->post('ques_5', TRUE),
                'ques_6'    =>  $this->input->post('ques_6', TRUE),
                'ques_7'    =>  $this->input->post('ques_7', TRUE),
                'ques_8'    =>  $this->input->post('ques_8', TRUE),
                'ques_9'    =>  $this->input->post('ques_9', TRUE),
                'ques_10'   =>  $this->input->post('ques_10', TRUE))

是否可以使用forforeach循环创建内容?

3 个答案:

答案 0 :(得分:2)

您可以像这样创建for循环:

$answers = array();
for($i = 1; $i <= 10; ++$i){
    $answers['ques_'.$i] = $this->input->post('ques_'.$i, TRUE);
}

答案 1 :(得分:2)

使用数组而不是ques_n为输入命名。

<input type="text" name="questions[]" value="value1"/>
<input type="text" name="questions[]" value="value2"/>
<input type="text" name="questions[]" value="value3"/>

然后你可以得到这样的数据:

$answers = $this->input->post('questions', TRUE);

根据rjcod的评论进行编辑:

你也可以像这样生成输入,并且仍然使用相同的php代码:

<input type="text" name="questions[0]" value="value1"/>
<input type="text" name="questions[1]" value="value2"/>
<input type="text" name="questions[2]" value="value3"/>
<!-- This 3 radio buttons are grouped, you can also wrap them in
fieldset if you want -->
<input type="radio" name="questions[3]" value="1"/>
<input type="radio" name="questions[3]" value="2"/>
<input type="radio" name="questions[3]" value="3"/>

答案 2 :(得分:0)

你可以试试这个:

 $data = array();
 $post_length = sizeof($_POST);

   for($i = 1; $i <= $post_length; ++$i){
        $data ['ques_'.$i] = $this->input->post('ques_'.$i, TRUE);
    }

或者你可以使用完全动态的。

$data = array();
foreach($_POST as $key=>$value)
    {
      $data [$key] = $this->input->post($key, TRUE);
      //or 
      //$data [$key] = $value;
    }
相关问题