1

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

2 Answers 2

1

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>';
}
Sign up to request clarification or add additional context in comments.

Comments

0

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]
        );
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.