ilhnctn
ilhnctn

Reputation: 2210

how to send array of array using JSON

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?

Upvotes: 1

Views: 261

Answers (2)

Ja͢ck
Ja͢ck

Reputation: 173642

Just change how you build the array. If you want to group by category:

Edit

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)
]

Then use json_encode on the end-result.

Btw, not sure why you store those buttons inside the object itself ;-)

Upvotes: 3

piyush
piyush

Reputation: 976

Use json_encode function. http://php.net/manual/en/function.json-encode.php

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

Upvotes: 3

Related Questions