简体   繁体   English

如果两个字段相同,如何使用JSON COUNT-SUM求和

[英]How can I sum values if two fields are the same using JSON COUNT - SUM

this is my JSON file. 这是我的JSON文件。

{"result":[
{"beer":"23","store":"1","table":"1"},
{"beer":"12","store":"1","table":"1"},
{"beer":"5","store":"1","table":"2"}]}

I want to sum beer if the store and table fields are the same. 如果商店和表字段相同,我想对啤酒求和。

The result should be be 2 records: 结果应为2条记录:

beer 35, store 1 table 1
beer 5, store 1 table 2

This is the MYSQL Query I use: 这是我使用的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));

Hope you need group by 希望你需要group by

$sql = "
    SELECT sum(beer) as beer, store, table 
    FROM data 
    GROUP BY store, table  
    ORDER BY beer DESC
";

To do this directly from the sql: 要直接从sql做到这一点:

$query = "SELECT sum(beer) as beer, store, table FROM data GROUP BY store, table " ; $ query =“选择sum(beer)作为啤酒,商店,表FROM数据GROUP BY商店,表”;

to sum it from the json: 从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 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM