2

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.

1
  • Think about using mysqli rather than mysql which is deprecated. Commented Jan 13, 2014 at 13:44

3 Answers 3

1
 $records = array();

 if($rows_query2 > 0) {
 while($r = mysql_fetch_array($query2_result)) {
      $records[$r['date']][] = array('name'=>$r['name'],'count'=>$r['count']);
 }
Sign up to request clarification or add additional context in comments.

Comments

0

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

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

Comments

0

Change while logic with below one

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.