这是mysql查询的结果
` date | link |sum
2015-06-29 |uploads/1_29_06_2015_9_18_37_image.jpg |6
2015-06-29 |uploads/1_29_06_2015_13_57_54_image.jpg|2
2015-06-30 |uploads/1_30_06_2015_0_26_44_image.jpg |2
2015-07-01 |uploads/1_01_07_2015_2_44_47_image.jpg |3
2015-07-01 |uploads/1_01_07_2015_5_15_47_image.jpg |4
2015-07-02 |uploads/1_02_07_2015_1_40_05_image.jpg |2`
有人可以帮我通过PHP生成一个格式如下的json。
[
{
"date": "2015-06-29",
"values": [{"image":"uploads/1_29_06_2015_9_18_37_image.jpg","sum":6},{"image":"uploads/1_29_06_2015_13_57_54_image.jpg","sum":2}]
},
{
"date": "2015-06-30 ",
"values": [{"link":"uploads/1_30_06_2015_0_26_44_image.jpg","sum":2}]
}
]
我希望将链接分组并在同一天汇总。
更新1:
这是我的代码:
<?php
$uid = $_SESSION['uid'];
$registerquery = mysql_query("select DATE(date) as dates,pic, sum(veg)+sum(fruit) as sum from diary where u_id = $uid and pic !='' group by date;");
$data = array();
foreach (mysql_fetch_row($registerquery) as $row) {
if (!array_key_exists($row['dates'], $data)) {
$data[$row['dates']] = array('date' => $row['dates'], 'values' => array());
}
$data[$row['dates']]['values'][] = array(
'image' => $row['pic'],
'sum' => $row['sum']
);
}
//this is your JSON
echo json_encode(array_values($data));
?>
但我似乎只得到第一个字符。
[{"date":"2","values":[{"image":"0","sum":"1"}]},{"date":"u","values":[{"image":"p","sum":"l"}]},{"date":"6","values":[{"image":"","sum":""}]}]
答案 0 :(得分:3)
假设$rows
包含所有已提取的行:
$data = array();
foreach ($rows as $row) {
if (!array_key_exists($row['DATE'], $data)) {
$data[$row['DATE']] = array('date' => $row['DATE'], 'values' => array());
}
$data[$row['DATE']]['values'][] = array(
'image' => $row['LINK'],
'sum' => $row['SUM']
);
}
//this is your JSON
echo json_encode(array_values($data));
答案 1 :(得分:0)
<?php include "connect.php"; ?>
<?php
$uid = $_SESSION['uid'];
$registerquery = mysql_query("select DATE(date) as dates,pic, sum(veg)+sum(fruit) as sum from diary where u_id = $uid and pic !='' group by date;");
$data = array();
while($row = mysql_fetch_array($registerquery)) {
// echo $row['dates']; echo " "; echo $row['pic']; echo " "; echo $row['sum']; echo "<br><br>";
if (!array_key_exists($row['dates'], $data)) {
$data[$row['dates']] = array('date' => $row['dates'], 'values' => array());
}
$data[$row['dates']]['values'][] = array(
'image' => $row['pic'],
'sum' => $row['sum']
);
}
echo json_encode(array_values($data));
?>