这是我的JSON文件。
{"result":[
{"beer":"23","store":"1","table":"1"},
{"beer":"12","store":"1","table":"1"},
{"beer":"5","store":"1","table":"2"}]}
如果商店和桌子字段相同,我想要加啤酒。
结果应该是2条记录:
beer 35, store 1 table 1
beer 5, store 1 table 2
这是我使用的MYSQL查询:
$sql = "SELECT * FROM data ORDER BY beer DESC";
$res = mysql_query($sql);
$result = array();
while( $row = mysql_fetch_array($res) )
array_push($result, array('beer' => $row[1],
'store' => $row[2],
'table' => $row[3]));
echo json_encode(array("result" => $result));
答案 0 :(得分:2)
希望您需要group by
$sql = "
SELECT sum(beer) as beer, store, table
FROM data
GROUP BY store, table
ORDER BY beer DESC
";
答案 1 :(得分:0)
直接从sql执行此操作:
$ query =“选择总和(啤酒)作为啤酒,商店,桌子 来自数据 GROUP BY商店,表“;
从json中总结出来:
$json_result = json_decode($json_var) ;
$result = array() ;
foreach($json_result->result as $key=>$value){
if(!isset($result[$value->store])){
$result[$value->store] = array() ;
$result[$value->store][$value->table] = $value->beer ;
}
else if(!isset($result[$value->store][$value->table])){
$result[$value->store][$value->table] = $value->beer ;
}
else{
$result[$value->store][$value->table] += $value->beer ;
}
}
$result will contain the json sum