1

我有一个功能,可以从数据库中获取一些数据并将其发布给我的客户。目前它以普通数组的形式发送数据(输出类似于 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" . )..`

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

4

2 回答 2

3

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

string json_encode ( mixed $value [, int $options = 0 ] )
于 2012-05-14T09:05:47.617 回答
3

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

编辑

代码更改为使用名称 => 键映射创建编号类别。

$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在最终结果上使用。

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

于 2012-05-14T09:11:24.810 回答