Storm Spirit
Storm Spirit

Reputation: 1520

How to do HTML array input with like this?

I have a laravel code that loop and this is the sample inputs

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

and it result like this

enter image description here

any idea how to do like this result?

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
                    )
        ....
    )

)

if there is no like this on <input>, how to do this on foreach loop to result like this?

What is your current Immigration status? Naturalized Citizen
Do you have a Green Card? Yes

Upvotes: 1

Views: 88

Answers (2)

RichardBernards
RichardBernards

Reputation: 3097

If can be assumed that all fields always exist, this should work:

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

If you can't however, you need to do validity checking:

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

Upvotes: 0

Machavity
Machavity

Reputation: 31624

I would just foreach over one array you have since the keys match for both questions and answers. You can then reference the key of the other array to get the current value

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

Upvotes: 1

Related Questions