序列化表单的数据并将其反序列化为关联数组


serialize the data of a form and deserialize it into an associative array

当我使用 $('#myForm').serialize() 发布表单的所有字段(它只包含许多组单选按钮)时,我得到这样的 POST 数据:

radio1=blue&radio2=red&radio3=white

但是我不知道如何在PHP中解码(反序列化)它以获得这样的关联数组:

$myArray = array("radio1"=>"blue", "radio2"=>"red", "radio3"=>"white");

编辑:这是html代码:

for( $i=1; $i<=$unknownNumber; $i++ ){
   echo("<input type='"radio'" name='""."radio".$i."'" value='"blue'" checked>");
   echo("<input type='"radio'" name='""."radio".$i."'" value='"red'">");
   echo("<input type='"radio'" name='""."radio".$i."'" value='"white'">");
}

下面是 js 代码:

$(document).ready(function() {
    $('input[name^="radio"]').on('click', function() {
        $.post( "process.php", $("#myForm").serialize(), function(data){
            alert('Good');
        });
    });
});

你可以在 php 中使用parse_str函数:

 $arr = array();
 parse_str('radio1=blue&radio2=red&radio3=white',$arr);
var_dump($arr);

PHP parse_str函数

在 php 中不需要(反序列化)使用$_POST['radio1'] (It contains the value 'blue')

$_POST type array()包含由 Ajax 发送或从提交发送的所有帖子数据

parse_str('radio1=blue&radio2=red&radio3=white',$postdata);
var_dump($postdata);

输出:

array(3) {
  ["radio1"]=>
  string(4) "blue"
  ["radio2"]=>
  string(3) "red"
  ["radio3"]=>
  string(5) "white"
}