在PHP中创建一个具有相同键和值的Sum的新数组

时间:2016-04-08 05:32:29

标签: php mysql arrays

Result from Database
(
    [ID] => 3167
    [dataID] => 1
    [data] => P01273
    [hours] => 1
    [month] => 1

)
(
    [ID] => 3168
    [dataID] => 1
    [data] => P01273
    [hours] => 1
    [month] => 2

)
(
    [ID] => 3191
    [dataID] => 2
    [data] => P01273
    [hours] => 10
    [month] => 1

)

(
    [ID] => 3196
    [dataID] => 2
    [data] => P01273
    [hours] => 10
    [month] => 2

)
(
    [ID] => 3189
    [dataID] => 2
    [data] => P00428
    [hours] => 22
    [month] => 2

)
(
    [ID] => 3189
    [dataID] => 2
    [data] => P004299
    [hours] => 22
    [month] => 2

)
if month and data are equal then calculate the SUM of hours
Need Output 
(
    [ID] => 3167
    [dataID] => 1
    [data] => P01273
    [hours] => 11 (adding 1+11)
    [month] => 1

)
(
    [ID] => 3168
    [dataID] => 1
    [data] => P01273
    [hours] => 11 (adding 1+11)
    [month] => 2

)
(
    [ID] => 3189
    [dataID] => 2
    [data] => P00428
    [hours] => 22
    [month] => 2

)
(
    [ID] => 3189
    [dataID] => 2
    [data] => P004299
    [hours] => 22
    [month] => 2

)

1 个答案:

答案 0 :(得分:0)

这是主要想法。 Haven没有执行脚本,所以如果有的话你必须修复bug。欢呼声。

  $newarray = array(); // global

    while($row = mysql_fetch_assoc($result)){

       if($idx = isdatasame($row)){
          $newarray[$idx]['hour'] += $row['hour']; // add hour to existing record
       }
       else{
          $newarray[] = $row;  // if record not in $newarray add new record
       }

    }

    function isdatasame($row){
      global $newarray;
      for($i=0; $i<COUNT($newarray); $i++){
        if($newarray[$i]['data']==$row['data'] && $newarray[$i]['month']==$row['month'] )
            return $i;
      }
      return false;
    }