pragaas
pragaas

Reputation: 43

To build a multi-dimensional json array in PHP

I want a multi-dimensional array in a specific json format from the table that is returned through an sql query. The table looks like this: (excuse the raw format)

| Date | Count | Name |

| 2013-12-19 | 252 | Value 1 |

| 2013-12-19 | 60 | Value 2 |

| 2013-12-19 | 8 | Value 3 |

| 2013-12-26 | 173 | Value 1 |

| 2013-12-26 | 32 | Value 2 |

| 2013-12-26 | 6 | Value 3 |

I want a multi-dimensional json array in the below mentioned format:

{2013-12-19: [{Name:"Value 1",Count:"252"},{Name:"Value 2",Count:"60"},{Name:"Value 3",Count:"8"}],

2013-12-26: [{Name:"Value 1",Count:"173"},{Name:"Value 2",Count:"32"},{Name:"Value 3",Count:"6"}] }

I tried a code but I'm facing trouble in adding all the date values inside that array. Here is the sample code that I tried:

    $query2_result = mysql_query($query2) or die(mysql_error());
    $rows_query2 = mysql_num_rows($query2_result);
    $records = array();

    if($rows_query2 > 0) {
     while($r = mysql_fetch_array($query2_result)) {
        if(!array_key_exists($r[date][name],$records[$r[date]])) {
                    $records[$r[date]][name] = array();

        }

         $records[$r[date]]["count"] = $r[count];
         $records[$r[date]]["name"] = $r[name];
      }
    }
    echo json_encode($records);

I'm getting only one array for each date mentioned. Like this:

{"2013-12-19":{"name":"Value 1","count":"775"},"2013-12-26":{"name":"Value 1","count":"397"}}

Kindle help me out. Thanks in davance.

Upvotes: 2

Views: 220

Answers (3)

codepiper
codepiper

Reputation: 109

Change while logic with below one

while($r = mysql_fetch_array($query2_result)) {
    $records[$r["date"]][]  = array(  "Name" => $r["name"], "Count" => $r["count"]);
}

Upvotes: 0

voodoo417
voodoo417

Reputation: 12101

 $records = array();

 if($rows_query2 > 0) {
 while($r = mysql_fetch_array($query2_result)) {
      $records[$r['date']][] = array('name'=>$r['name'],'count'=>$r['count']);
 }

Upvotes: 1

Samuil Banti
Samuil Banti

Reputation: 1795

I think all you need to do to add all records for a given date to sub-array is this:

$records[$r[date]][] = $r;

Upvotes: 0

Related Questions