如何使用JSON发送数组数组

时间:2012-05-14 09:02:47

标签: php json

我有一个函数可以从数据库和帖子中获取一些数据给我的客户端。目前它将数据作为普通数组发送(输出类似于MyArray(a,b,c,d ..)),但我希望它是MyArray(a(b,c,d))..就像Castegory(名称,ID,订单..)..任何人都可以请帮助..这是我已经使用过的版本的代码

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;
    }

编辑请稍微详细一点.. 当我解析这个我得到这样的东西:

"Vaule"( "Key1": "Value1" "Key2": "Value2" .

但我想要的是像

这样的东西
 `"Category0":( "Key1": "Value1", "Key2": "Value2" . ) 

"Category1":( "Key1": "Value1", "Key2": "Value2" . )..`

如何发送带键值对的多维数组?

2 个答案:

答案 0 :(得分:3)

使用json_encode函数。 http://php.net/manual/en/function.json-encode.php

string json_encode ( mixed $value [, int $options = 0 ] )

答案 1 :(得分:3)

只需更改构建阵列的方式即可。如果您想按类别分组:

修改

使用name =>更改代码以创建编号类别关键地图。

$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++;
}

这会生成如下数组:

<category 1>: [
    (CatName1, Id1, name1, ordernr1)
    (CatName1, Id2, name2, ordernr2)
],
<category 2>: [
    (CatName2, Id3, name3, ordernr3)
    (CatName2, Id4, name4, ordernr4)
]

然后在最终结果上使用json_encode

顺便说一句,不知道为什么要将这些按钮存储在对象本身内; - )