如何在laravel控制器中对具有相同键值的下面数组中的值求和

时间:2018-02-26 02:22:33

标签: arrays laravel

如何对laravel控制器中具有相同键值的下面数组中的值求和 我想在键['x']中的相同日期对值进行求和,并按日期

显示

此控制器

        $MB = DB::table('tbPCSInfo')
        ->distinct()
        ->where('UserID','=',1)
        ->select('MBxID')
        ->get();

    foreach($MB as $mbxid)
    {

    $Inv = tbPCSInfo::with('tbPcsStatusDescripts')
        ->distinct()
        ->where('MBxID', '=', $mbxid->MBxID)
        ->select('PcsID')                    
        ->get(); 

    foreach($Inv as $pcsid)
            {
                $data[] = DB::table('tbPCSInfo')
                ->whereYear('Time' ,'=',2018)  
                ->where('MBxID' ,'=',$mbxid->MBxID)
                ->where('PcsID' ,'=', $pcsid->PcsID)          
                ->whereMonth('Time' ,'=',2)
                ->select(DB::raw('UNIX_TIMESTAMP(DATE(Time))*1000 AS x 
,MAX(PConsumption) - MIN(PConsumption) AS y '))
                // ->select(DB::raw('UNIX_TIMESTAMP(DATE(Time))*1000 AS x'))
                // ->select(DB::raw('MAX(PConsumption) - MIN(PConsumption) AS 
y'))    
                // ->select(DB::raw('MAX(PConsumption)- min AS y'))
                ->groupBy(DB::raw('UNIX_TIMESTAMP(DATE(Time))*1000') )
                // ->groupBy('x')
                ->get();   
            }                 
    }
    dump($data);   

这个来自laravel控制器的数组我希望在键['x']中的相同日期对值进行求和,并按日期显示

    array:3 [▼
0 => Collection {#1360 ▼
#items: array:5 [▼
  0 => {#1292 ▼
    +"x": "1518973200000"
    +"y": "1"
  }
  1 => {#1293 ▼
    +"x": "1519059600000"
    +"y": "112"
  }
  2 => {#1294 ▼
    +"x": "1519146000000"
    +"y": "98"
  }
  3 => {#1295 ▼
    +"x": "1519232400000"
    +"y": "86"
  }
  4 => {#1296 ▼
    +"x": "1519318800000"
    +"y": "18"
  }
]
}
1 => Collection {#1461 ▼
#items: array:5 [▼
  0 => {#1393 ▼
    +"x": "1518973200000"
    +"y": "1"
  }
  1 => {#1394 ▼
    +"x": "1519059600000"
    +"y": "111"
  }
  2 => {#1395 ▼
    +"x": "1519146000000"
    +"y": "100"
  }
  3 => {#1396 ▼
    +"x": "1519232400000"
    +"y": "86"
  }
  4 => {#1397 ▼
    +"x": "1519318800000"
    +"y": "18"
  }
]

我希望看到这样的结果(//数组x中的y之和)

array [▼
  0 => {#1292 ▼
    +"x": "1518973200000"
    +"y": "??" //Sum of y in array group by x  
  }
  1 => {#1293 ▼
    +"x": "1519059600000"
    +"y": "112" //Sum of y in array group by x  
  }
  2 => {#1294 ▼
    +"x": "1519146000000"
    +"y": "98" //Sum of y in array group by x  
  }
  3 => {#1295 ▼
    +"x": "1519232400000"
    +"y": "86" //Sum of y in array group by x  
  }
  4 => {#1296 ▼
    +"x": "1519318800000"
    +"y": "18" //Sum of y in array group by x  
  }

和这个数组结果 enter image description here

0 个答案:

没有答案