【问题标题】:convert POST array data to json format将 POST 数组数据转换为 json 格式
【发布时间】:2018-03-16 19:29:11
【问题描述】:

我正在使用 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[]">

//数据2:

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

我希望结果如下:

{id:1,name:"aa",stuff:"cc"},{id:2,name:"dd",stuff:"ff"}

我知道如果我们使用 json_encode($_POST,true) 我将拥有:

{"id":["1","2"],"name":["aa","dd"],"stuff":["cc","ff"]}

我可以通过 js 使用 get 方法 not post

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

检查我的解决方案 https://jsfiddle.net/cqvny3th/

或者如果我们使用 http_build_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

问候

【问题讨论】:

  • 第一个结果不是有效的 JSON。

标签: php


【解决方案1】:

绝对不如@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;
}

所以如果$_POST 在提交时看起来像:

[
    'id' => [1, 2],
    'name' => ['foo', 'bar'],
    'stuff' => [3]
];

代码产生:

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

【讨论】:

    【解决方案2】:

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

    <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]">
    

    这将正确地对数据进行分组。在json_encode 之前使用array_values,这样您将获得一个对象数组而不是一个对象。

    echo json_encode(array_values($_GET));
    

    【讨论】:

    • 真的不知道你能做到这一点。哇,每天都是上学日。
    • 我确信我一定是在某个时候在 Stack Overflow 的某个地方学到了这一点。 :)
    【解决方案3】:

    你能做这样的事情吗?

    $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 );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-11
      • 2016-08-05
      • 2011-07-03
      • 1970-01-01
      • 2014-02-27
      • 2011-08-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多