phpjqueryarraysajaxserializearray

How can I serializeArray with a structure based on key value?


I am creating an Array from a form via serializeArray() in jQuery:

var form = $(this).closest('form');
var formData = form.serializeArray();

If I output this with alert(formData.toSource()); I get the result:

[{name:"form[username]", value:"1"}, {name:"form[email]", value:"1@12.sw"}, {name:"form[is_active]", value:"1"}, {name:"form[plainPassword][first]", value:""}, {name:"form[plainPassword][second]", value:""}, {name:"form[id]", value:"9"}, {name:"form[_token]", value:"Mk"}]

If I capture the data via Ajax to php with $data = $request->request->get('data');I get the following Array as a result:

array(7) {
  [0]=>
  array(2) {
    ["name"]=>
    string(14) "form[username]"
    ["value"]=>
    string(1) "1"
  }
  [1]=>
  array(2) {
    ["name"]=>
    string(11) "form[email]"
    ["value"]=>
    string(7) "1@12.sw"
  }
  [2]=>
  array(2) {
    ["name"]=>
    string(15) "form[is_active]"
    ["value"]=>
    string(1) "1"
  }
  [3]=>
  array(2) {
    ["name"]=>
    string(26) "form[plainPassword][first]"
    ["value"]=>
    string(0) ""
  }
  [4]=>
  array(2) {
    ["name"]=>
    string(27) "form[plainPassword][second]"
    ["value"]=>
    string(0) ""
  }
  [5]=>
  array(2) {
    ["name"]=>
    string(8) "form[id]"
    ["value"]=>
    string(1) "9"
  }
  [6]=>
  array(2) {
    ["name"]=>
    string(12) "form[_token]"
    ["value"]=>
    string(43) "Mk"
  }
}

The array that I would actually need is something like this:

  array(2) {
    ["form[username]"]=>
    string(14) "1"
    ["form[email]"]=>
    string(1) "1@12.sw"
    ["form[is_active]"]=>
    string(1) "1"
    ["form[plainPassword][first]"]=>
    string(0) ""
    ["form[plainPassword][second]"]=>
    string(0) ""
    ["form[id]"]=>
    string(1) "9"
    ["form[id]"]=>
    string(2) "Mk"
  }

So is it possible to actually serialize the Array differently? What is the best way to achieve the array I would need?


Solution

  • foreach($data as $i) { $newData[$i['name']] = $i['value']; }
    

    $newData is now like you wanted it to be.