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

288 Views Asked by At

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:"[email protected]"}, {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) "[email protected]"
  }
  [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) "[email protected]"
    ["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?

2

There are 2 best solutions below

0
On BEST ANSWER
foreach($data as $i) { $newData[$i['name']] = $i['value']; }

$newData is now like you wanted it to be.

0
On

As the comments suggest, there is no built-in way of doing so. You either have to loop through the array and build the object yourself, or more common, just use .serialize() and handle the parameter interpretation in php directly.