简体   繁体   中英

Grouping elements by date

I have a code below:

 for($j=0; $j<=odbc_fetch_row($result); $j++){  


                   $date = odbc_result($result, 'DATE');
                    $A = odbc_result($result, 'A');
                   $B = odbc_result($result, 'B');
                   $C = odbc_result($result, 'C');
                   $D = odbc_result($result, 'D');
                   $E= odbc_result($result, 'E');

                   echo $date." ".$A." ".$B." ".$C." ".$D." ".$E."<br/>";
}
 DATE ABCDE 20140101 0 8225.12 0 0 0 20140101 18483.28 0 0 0 0 20140101 0 0 12275.49 0 0 20140101 0 0 0 3013.50 0 20140101 0 0 0 0 4552.20 20140102 0 3612.30 0 0 0 20140102 6850.10 0 0 0 0 20140102 0 0 5695.45 0 0 20140102 0 0 0 3291.80 0 20140102 0 0 0 0 2006.20 20140103 0 2684.10 0 0 0 20140103 13342.26 0 0 0 0 20140103 0 0 6981.14 0 0 20140103 0 0 0 3887.93 0 20140103 0 0 0 0 5117.50 

How do I group the elements by the date like the following?

DATE ABCDE

20140101 18483.28 8225.12 12275.49 3013.50 4552.20
20140102 6850.10 3612.30 5695.45 3291.80 2006.20

Try

$result = array();
 for($j=0; $j<=odbc_fetch_row($result); $j++){
      $date = odbc_result($result, 'DATE');
      $A = odbc_result($result, 'A');
      $B = odbc_result($result, 'B');
      $C = odbc_result($result, 'C');
      $D = odbc_result($result, 'D');
      $E= odbc_result($result, 'E');
      $row = array($date,$A,$B,$C,$D,$E);
      for($i=0;$i<count($row);$i++){
         if($row[$i]>0) {
             $result[$date][$i] = $row[$i];
         }
      }  
 }

See demo here

You can do it in mysql query directly as below assuming your data pattern is same meaning for each row any one of the columns in a,b,c,d,e will have a value and rest all 0 as

SELECT `date`,
       max(`a`) as `a`,
       max(`b`) as `b`,
       max(`c`) as `c`,
       max(`d`) as `d`,
       max(`e`) as `e` 
 FROM `test`
GROUP BY `date`

So after executing the query you get the data by loop

check here

http://sqlfiddle.com/#!2/4952f0/12

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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