John Davidson

php - Iterate over a collection in laravel and aggregate it

0 comments
Message:


I've a sample collection


#items: array:4 [▼
0 => Collection {#465 ▼
#items: array:2 [▼
"id" => 1
"user_id" => 5
]
}
1 => Collection {#455 ▼
#items: array:2 [▼
"id" => 2
"user_id" => 5
]
}
2 => Collection {#419 ▼
#items: array:2 [▼
"id" => 3
"user_id" => 1
]
}
3 => Collection {#410 ▼
#items: array:2 [▼
"id" => 4
"user_id" => 1
]
}
]
}

how can I aggregate the above collection to the below collection. It is the count of ids for every user_id's.


#items: array:2 [▼
0 => Collection {#465 ▼
#items: array:2 [▼
"user_id" => 1
"count" => 2
]
}
1 => Collection {#455 ▼
#items: array:2 [▼
"user_id" => 5
"count" => 2
]
}
]
}

Any suggestions would be appreciated.



My Answer:
php
$collection = collect([
['name' => 'John', 'age' => 30],
['name' => 'Jane', 'age' => 25],
['name' => 'Alice', 'age' => 35],
]);

$totalAge = $collection->reduce(function ($carry, $item) {
return $carry + $item['age'];
}, 0);

echo $totalAge; // Output: 90

Rate this post

4 of 5 based on 3254 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us