我通过$("input").serializeArray();
这是我的输出:
0: Object { name: "id", value: "9" }
1: Object { name: "name", value: "Fred" }
2: Object { name: "quantity", value: "1" }
我通过ajax将此对象发送到我的php页面。我通过$_POST['myarray']
得到它。输出是:
[0]=>
array(2) {
["name"]=>
string(2) "id"
["value"]=>
string(1) "9"
}
[1]=>
array(2) {
["name"]=>
string(4) "name"
["value"]=>
string(14) "Fred"
}
[2]=>
array(2) {
["name"]=>
string(8) "quantity"
["value"]=>
string(1) "1"
}
但我需要的输出是:
array(3) {
["id"]=>
string(1) "9"
["name"]=>
string(1) "Fred"
["quantity"]=>
string(1) "1"
}
答案 0 :(得分:2)
要在PHP中获取所需的数据结构,您需要以这种格式从JS代码发送单个对象:
{
id: "9",
name: "Fred",
quantity: "1"
}
为此,您可以使用当前数组中对象的键来构建新对象,如下所示:
var serializedForm = [
{ name: "id", value: "9" },
{ name: "name", value: "Fred" },
{ name: "quantity", value: "1" }
];
var o = {};
serializedForm.forEach((k) => {
o[k.name] = k.value;
});
console.log(o);

答案 1 :(得分:2)
在服务器端,您可以在循环中选择键/值对并创建所需的数组格式:
$formObj = $_POST['myarray'];
$myObj = array();
foreach($formObj as $array){
$myObj[$array["name"]] = $array["value"];
}
var_dump($myObj); // New object with key/value pair