Php 将POST数组数据转换为json格式

Php 将POST数组数据转换为json格式,php,Php,我使用POST方法,希望PHP脚本以JSON格式返回数据 //数据1: <input type="text" value="1" name="id[]"> <input type="text" value="aa" name="name[]"> <input type="text" value="cc" name="stuff[]"> 我理解如果我们使用json_encode($_POST,true),我将: {"id":["1","2"],"name":[

我使用POST方法,希望PHP脚本以JSON格式返回数据

//数据1:

<input type="text" value="1" name="id[]">
<input type="text" value="aa" name="name[]">
<input type="text" value="cc" name="stuff[]">
我理解如果我们使用json_encode($_POST,true),我将:

{"id":["1","2"],"name":["aa","dd"],"stuff":["cc","ff"]}
我可以通过js使用get方法而不是post来实现这一点

id[]=1&name[]=aa&stuff=cc&id[]=2&name[]=dd&stuff[]=ff
检查我的解决方案

或者,如果我们使用http\u build\u query从post方法生成url,结果是:

id[]=1&id[]=2&name[]=aa&name[]=dd&stuff=cc&stuff[]=ff
但我的解决方案仅适用于:

id[]=1&name[]=aa&stuff=cc&id[]=2&name[]=dd&stuff[]=ff

如果可以,请重命名您的输入

<input type="text" value="1" name="data1[id]">
<input type="text" value="aa" name="data1[name]">
<input type="text" value="cc" name="data1[stuff]">

<input type="text" value="2" name="data2[id]">
<input type="text" value="dd" name="data2[name]">
<input type="text" value="ff" name="data2[stuff]">

肯定不如@Don't Panic的解决方案优雅,但如果您想/需要保持您的
name
属性的原样,这将起作用:

//prep
$repeated_post_vars = ['id', 'name', 'stuff'];
$arr = [];

//find which column has the most values, just in case they're not all equal
$num_items = max(array_map(function($col) {
    return !empty($_POST[$col]) ? count($_POST[$col]) : 0;
}, $repeated_post_vars));

//iterate over value sets
for ($g=0; $g<$num_items; $g++) {
    foreach($repeated_post_vars as $col)
        $tmp[$col] = !empty($_POST[$col][$g]) ? $_POST[$col][$g] : null;
    $arr[] = $tmp;
}
该代码生成:

[{"id":1,"name":"foo","stuff":3},{"id":2,"name":"bar","stuff":null}]

你能这样做吗

$list = array();
for ($i=0; $i<count($_POST['id']); $i++) {
    $item = new stdClass();
    foreach ($_POST as $key => $values)
        $item->{$key} = $values[$i];
    $list[] = $item;
}

print json_encode( $list );
$list=array();
对于($i=0;$i$值)
$item->{$key}=$values[$i];
$list[]=$item;
}
打印json_编码($list);

第一个结果不是有效的JSON。你根本不知道你可以这么做。哇,每天都是上学的日子。我肯定我一定在某个时候在堆栈溢出的某个地方学到了这一点。:)
//prep
$repeated_post_vars = ['id', 'name', 'stuff'];
$arr = [];

//find which column has the most values, just in case they're not all equal
$num_items = max(array_map(function($col) {
    return !empty($_POST[$col]) ? count($_POST[$col]) : 0;
}, $repeated_post_vars));

//iterate over value sets
for ($g=0; $g<$num_items; $g++) {
    foreach($repeated_post_vars as $col)
        $tmp[$col] = !empty($_POST[$col][$g]) ? $_POST[$col][$g] : null;
    $arr[] = $tmp;
}
[
    'id' => [1, 2],
    'name' => ['foo', 'bar'],
    'stuff' => [3]
];
[{"id":1,"name":"foo","stuff":3},{"id":2,"name":"bar","stuff":null}]
$list = array();
for ($i=0; $i<count($_POST['id']); $i++) {
    $item = new stdClass();
    foreach ($_POST as $key => $values)
        $item->{$key} = $values[$i];
    $list[] = $item;
}

print json_encode( $list );