PHP json_en将多个数组编码为一个对象 [英] PHP json_encode multiple arrays into one object

查看:98
本文介绍了PHP json_en将多个数组编码为一个对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在一个JSON对象中返回多个数组,并且在语法上遇到一些困难.一个Android应用接收来自多个表的更新,希望在一个响应中返回.

I am trying to return multiple arrays in one JSON object and having some difficulty with the syntax. An Android app receives updates from multiple tables, that I wish to be returned in one response.

当前,这是我编码各种结果集的方式:

Currently, this is how I am encoding the various result sets:

$json=json_encode(array($table1, $table2, $table3, $table4, $table5, $table6));

数据以以下格式返回:

[{"table1":[{...}]},{"table2":[{...}]},...]

在Android代码中,我希望能够将其解析为JSONObject,然后可以从名称中检索每个数组,而不是将其解析为JSONArray并按位置检索每个子数组. JSON响应看起来像这样:

In the Android code, I'd like to be able to parse it as a JSONObject, from which I can then retrieve each array by name instead of parsing it as a JSONArray and retrieving each sub array by position. The JSON response would look like this instead:

    {{"table1":[{...}]},{"table2":[{...}]},...}

似乎我要做的只是将结果数组包装在一个对象中,而不是在PHP端包装一个数组,但是尽管我设法盲目地将足够多的PHP代码拼凑到一起,但我无法做到这一点似乎弄清楚了最后一步.

It seems all I need to do is wrap the results arrays in an object, instead of an array on the PHP side, but although I've managed to blindly cobble together enough PHP code to get this far, I can't seem to figure out that final step.

推荐答案

您的最后一个示例不是有效的JSON,花括号始终表示带有键的对象;相反,您将其视为数组.如果您想要一个对象,则可以在PHP中将键添加到数组中,如下所示:

Your last example is not valid JSON, curly braces always mean object with keys; instead you're treating it as an array. If you want an object, then add keys to the array in PHP like so:

$json=json_encode(array('a' => $table1, 'b' => $table2, 'c' => $table3));

这将产生

{"a":{"table1":[{...}]},"b":{"table2":[{...}]},...}

似乎正是您想要的.

这篇关于PHP json_en将多个数组编码为一个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆