如何使用JSON发送数组的数组 [英] how to send array of array using JSON
问题描述
我有一个功能,可以从数据库中获取一些数据并将其发布到我的客户端.目前,它以普通数组形式发送数据(输出类似于MyArray(a,b,c,d ..)),但我希望它成为MyArray(a(b,c,d)). Castegory(名称,ID,订单..)..谁能帮忙..这是我已经使用的版本的代码
i have a function which brings me some data from database and posts to my client. At the moment it sends data as a normal array(output is something like MyArray (a,b,c,d..)), but i want it to be MyArray (a(b,c,d)).. As like Castegory(Name, ID, Order..).. Can anyone please Help..Here is my code for already used version
public function get_button_template()
{
$this->q = "SELECT * FROM button_template ORDER BY order_number ASC";
$this->r = mysql_query($this->q);
if(mysql_num_rows($this->r) > 0)
{
while($this->f = mysql_fetch_assoc($this->r))
{
$this->buttons[$this->i]["ID"] = $this->f["ID"];
$this->buttons[$this->i]["name"] = $this->f["button_name"];
$this->buttons[$this->i]["category"] = $this->f["button_category"];
$this->buttons[$this->i]["order_number"] = $this->f["order_number"];
$this->i++;
}
}
return $this->buttons;
}
编辑请稍作详细说明. 当我解析这个时,我得到的是这样的:
EDIT A little öore detail please.. when i parsed this i get something like this:
"Vaule"( "Key1": "Value1" "Key2": "Value2" .
但是我想要的是类似的东西
But what i want is omething like
`"Category0":( "Key1": "Value1", "Key2": "Value2" . )
"Category1":( "Key1": "Value1", "Key2": "Value2" . )..`
如何发送带有键值对的多维数组?
How can i send a multidimentional array with key-value pairs?
推荐答案
只需更改构建数组的方式.如果要按类别分组:
Just change how you build the array. If you want to group by category:
修改
更改代码以使用名称=>键映射创建编号类别.
Code changed to create numbered categories using a name => key map.
$category_map = array(); $cat_nr = 0;
while ($this->f = mysql_fetch_assoc($this->r)) {
if (!isset($category_map[$this->f["button_category"]])) {
$category_key = "Category{$cat_nr}";
$category_map[$this->f["button_category"]] = $category_key;
++$cat_nr;
} else {
$category_key = $category_map[$this->f["button_category"]];
}
$this->buttons[$category_key]][] = array(
'category' => $this->f["button_category"],
"ID" => $this->f["ID"],
"name" => $this->f["button_name"],
"order_number" => $this->f["order_number"],
);
$this->i++;
}
这会产生一个像这样的数组:
This produces an array like:
<category 1>: [
(CatName1, Id1, name1, ordernr1)
(CatName1, Id2, name2, ordernr2)
],
<category 2>: [
(CatName2, Id3, name3, ordernr3)
(CatName2, Id4, name4, ordernr4)
]
然后在最终结果上使用 json_encode
.
Then use json_encode
on the end-result.
顺便说一句,不确定为什么将这些按钮存储在对象本身内;-)
Btw, not sure why you store those buttons inside the object itself ;-)
这篇关于如何使用JSON发送数组的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!