Im not sure how to go about this, i need to get data from a table and sum the values of each field together where the ID is the same.
Things I Have Tried
$users = User::all();
$array = [];
foreach($users as $user)
{
array_push($array, [$user->account_id => $user->amount]);
}
Other than that im not too sure how to go about this! Here is the data that i pull from the database.
0: {1: 100.00}
1: {1: 100.00}
2: {2: 100.00}
3: {2: 100.00}
This is the output i want
0: {1: 200.00}
1: {2: 200.00}
This is all i need nothing else I feel like its really simple but I have no clue, any help and guidance will be appreciated, any further information needed will be provided.
Try this way:
<?php
User::groupBy('account_id')
->selectRaw('sum(amount) as sum, account_id')
->lists('sum','account_id');
EDIT
Since ->lists()
is now deprecated in laravel 5.2+ it should now be ->pluck()
, just for reference
If you want use PHP to group and sum it try:
$users = array(
array(
"account_id" => 1,
"amount" => 100
),
array(
"account_id" => 1,
"amount" => 100
),
array(
"account_id" => 2,
"amount" => 100
),
array(
"account_id" => 2,
"amount" => 100
),
array(
"account_id" => 2,
"amount" => 100
),
array(
"account_id" => 2,
"amount" => 100
)
);
$response = array();
foreach ($users as $usersIndex => $usersValue) {
if (!isset($response[$usersValue["account_id"]])) {
$response[$usersValue["account_id"]][$usersValue["account_id"]] = 0;
}
$response[$usersValue["account_id"]][$usersValue["account_id"]] += $usersValue["amount"];
}
$response = array_values($response);
var_dump($response);
output:
array(2) { [0]=> array(1) { [1]=> int(200) } [1]=> array(1) { [2]=> int(400) } }
But for that operation you should use groupBy and sum query.
This is one example:
$users = DB::table('users')
->select('id', DB::raw('SUM(amount) as total_amount'))
->groupBy('id')
->get();