1

How can I get this:

(
[0] => Array
    (
        [name] => variation
        [value] => variation1
    )

[1] => Array
    (
        [name] => variationid
        [value] => 70105
    )

[2] => Array
    (
        [name] => fullName
        [value] => 
    )

[3] => Array
    (
        [name] => address
        [value] => 
    )

[4] => Array
    (
        [name] => country
        [value] => usa
    )

[5] => Array
    (
        [name] => state
        [value] => Utah
    )

to look like this:

$fields['variation']=>variation1[variationid]=>70105.. etc

I tried:

foreach($_POST['fields'] as $key => $value){
    $fields[$key] = $value;
}

I thought this should work, but it gives it back to me looking the exact same way. This is just a serializedArray() from jquery passed into POST; I basically just want to be able to access it using the $fields['variation'] accessing. But it's making it difficult.

1 Answer 1

3

You aren't using the nested array correctly, $value holds the array with name and value and since $key (0,1,...) is not needed, you don't even need to define it.

foreach ($_POST['fields'] as $data) {
    $fields[ $data['name'] ] = $data['value'];
}
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you. That works, and it seems obvious now that you show it. As a side comment, is it possible to make jQuery send the form data as a one level array into post, just as the browser would? Instead of having to fix it like this in php once you receive it?
That should be no problem but depends on how exactly you use jQuery to send a POST request
<form class=myform> <input type=hidden name=variationid value=70105/> <input name=fullName value=myname/> etc.. $form = $('#myForm'); $fields = $form.serializeArray(); $.post("handler.php", "fields": $fields); Sorry i don't know how to put line breaks in... @kingkero
Ah ok, I honestly don't know if you can do this without ending up writing your own JS method. Research this topic and (if you didn't find a solution) ask another question on SO ;)

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.