从JSON格式化多维数组

时间:2014-07-15 13:28:00

标签: php arrays json symfony multidimensional-array

我的应用程序以这种格式从表单接收JSON:

{"loc[criteria][0][row][0][field]":"120","loc[criteria][0][row][0][chan]":"any","loc[criteria][0][row][0][network]":"any","loc[criteria][0][row][0][op]":"lt","loc[criteria][0][row][0][value]":"","loc[criteria][0][match]":"all","loc[match]":"all"}

当我运行json_decode($ json,TRUE)时,我得到一个单维数组:

 Array (
[loc[criteria][0][row][0][field]] => 120
[loc[criteria][0][row][0][chan]] => any
[loc[criteria][0][row][0][network]] => any
[loc[criteria][0][row][0][op]] => lt
[loc[criteria][0][row][0][value]] =>
[loc[criteria][0][match]] => all
[loc[match]] => all    
)

输入可以变得更大,有许多行和标准。我想将JSON转换为多维数组,如下所示:

 Array (
 criteria => Array (
      0 => Array (
        row => Array (
           0 => Array (
              field => 120
... etc...

转换此内容的正确方法是什么?

- 更新 -

输入来自序列化由Symfony2创建的表单。这是javascript:

var array = $('#search-form').serializeArray();
var json = {};

jQuery.each(array, function() {
    json[this.name] = this.value || '';
});

var ajaxInput=JSON.stringify(json);  //this is what gets passed to the server

这是Symfony2表单生成的字段的示例:

<input type="text" id="loc_criteria_0_row_0_value" name="loc[criteria][0][row][0][value]" placeholder="Value">

1 个答案:

答案 0 :(得分:1)

我相信这就是你所需要的:

$output_array = parse_json_input_form_array('{"loc[criteria][0][row][0][field]":"120","loc[criteria][0][row][0][chan]":"any","loc[criteria][0][row][0][network]":"any","loc[criteria][0][row][0][op]":"lt","loc[criteria][0][row][0][value]":"","loc[criteria][0][match]":"all","loc[match]":"all"}');

function parse_json_input_form_array($json) {
    $decoded_array = json_decode($json, true);

    foreach ($decoded_array as $key => $value) {
        $items[] = urlencode($key) . '=' . urlencode($value);
    }

    $items = implode("&", $items);

    parse_str($items, $parsed_items);

    return $parsed_items;
}