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)
我希望从通过sql查询返回的表中获得一个特定json格式的多维数组。这个表看起来是这样的:(不好意思是原始格式)
| Date | Count | Name |
|日期|计数|名称|
| 2013-12-19 | 252 | Value 1 |
| 2013-12-19 | 252 |值1 |
| 2013-12-19 | 60 | Value 2 |
| 2013-12-19 | 60 |值2 |
| 2013-12-19 | 8 | Value 3 |
| 2013-12-19 | 8 | 3 |值
| 2013-12-26 | 173 | Value 1 |
| 2013-12-26 | 173 |值1 |
| 2013-12-26 | 32 | Value 2 |
| 2013-12-26 | 32 |值2 |
| 2013-12-26 | 6 | Value 3 |
| 2013-12-26 | 6 | 3 |值
I want a multi-dimensional json array in the below mentioned format:
我想要一个多维json数组,格式如下:
{2013-12-19: [{Name:"Value 1",Count:"252"},{Name:"Value 2",Count:"60"},{Name:"Value 3",Count:"8"}],
{ 2013-12-19:[{名称:“1”,数:" 252 " },{名称:“值2”,数:“60”},{名称:“价值3”,数:“8”}),
2013-12-26: [{Name:"Value 1",Count:"173"},{Name:"Value 2",Count:"32"},{Name:"Value 3",Count:"6"}] }
2013-12-26:[{名称:“1”,数:" 173 " },{名称:“值2”,数:“32”},{名称:“价值3”,数:“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"}}
{“2013-12-19”:{“名称”:“1”,“数”:" 775 " },“2013-12-26”:{“名称”:“1”,“数”:" 397 " } }
Kindle help me out. Thanks in davance.
Kindle帮帮我。由于davance。
3 个解决方案
#1
1
$records = array();
if($rows_query2 > 0) {
while($r = mysql_fetch_array($query2_result)) {
$records[$r['date']][] = array('name'=>$r['name'],'count'=>$r['count']);
}
#2
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;
#3
0
Change while logic with below one
当逻辑在1以下时更改
while($r = mysql_fetch_array($query2_result)) {
$records[$r["date"]][] = array( "Name" => $r["name"], "Count" => $r["count"]);
}
#1
1
$records = array();
if($rows_query2 > 0) {
while($r = mysql_fetch_array($query2_result)) {
$records[$r['date']][] = array('name'=>$r['name'],'count'=>$r['count']);
}
#2
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;
#3
0
Change while logic with below one
当逻辑在1以下时更改
while($r = mysql_fetch_array($query2_result)) {
$records[$r["date"]][] = array( "Name" => $r["name"], "Count" => $r["count"]);
}