如何用这样的HTML数组输入?

时间:2016-01-27 14:01:57

标签: php html html5 input

我有一个循环的laravel代码,这是示例输入

<input type="hidden" value="{{ $question['question'] }}" name="custom_form[question][{{ $question['name'] }}]" />
<input type="text" name="custom_form[answer][{{ $question['name'] }}]" />

,结果就像这样

enter image description here

任何想法如何做到这样的结果?

Array
(
    (
        [immigration_status] => Array
                    (
                        [question]  => What is your current Immigration status?
                        [answer]    => Naturalized Citizen
                    )
        [green_card] => Array
                    (
                        [question]  => Do you have a Green Card?
                        [answer]    => Yes
                    )
        ....
    )

)

如果在<input>上没有这样的话,那么如何在foreach循环上执行此操作会产生这样的结果?

  

您目前的移民身份是什么?归化公民
      你有绿卡吗?是

2 个答案:

答案 0 :(得分:1)

我只会foreach超过一个数组,因为密钥匹配问题和答案。然后,您可以引用另一个数组的键来获取当前值

foreach($_POST['custom_form']['question'] as $key => $question) {
     echo htmlentities($question . ' ' . $_POST['custom_form']['answer'][$key]) . '<br>';
}

答案 1 :(得分:0)

如果可以假设所有字段始终存在,则应该有效:

$transposed = [];
foreach($arr['question'] as $key => $value) {
    $transposed[$key] = array('question' => $value, 'answer' => $arr['answer'][$key]);
}

但是,如果不能,则需要进行有效性检查:

$transposed = [];
foreach($arr['question'] as $key => $value) {
    if (array_key_exists($key, $arr['answer'])) {
        $transposed[$key] = array(
            'question' => $value,
            'answer'   => $arr['answer'][$key]
        );
    }
}