John Davidson

laravel - I need countBy to include "zero" occurrences to keep the array length in PHP

0 comments
Message:


I'm using the Laravel Eloquent's countBy( $key_name ) method on this Collection:

(Values can only be 1, 2, 3, 4 or 5).


$collection = [
{
"atencionMesero": "4",
"rapidezServicio": "2",
"calidadComida": "1",
"experienciaGeneral": "5"
},
{
"atencionMesero": "4",
"rapidezServicio": "2",
"calidadComida": "3",
"experienciaGeneral": "5"
},
{
"atencionMesero": "5",
"rapidezServicio": "5",
"calidadComida": "5",
"experienciaGeneral": "5"
},
]

So if I use $collection->countBy( 'rapidezServicio' ) I get this result:


{
"2": 2,
"5": 1,
}

But I need a function to include the "zero" occurrence, like so:


{
"1": 0,
"2": 2,
"4": 0,
"5": 1,
"3": 0
}

The order doesn't matter, I can simply use ksort() on the final result, but I've been struggling for days to make it work like this.


Thanks in advance.



My Answer:
You can achieve the desired result by creating a custom function to count the occurrences of each value in the collection and then filling in the missing values with a count of 0. Here's an example of how you can do this:

php
$collection = collect([
[
"atencionMesero" => "4",
"rapidezServicio" => "2",
"calidadComida" => "1",
"experienciaGeneral" => "5"
],
[
"atencionMesero" => "4",
"rapidezServicio" => "2",
"calidadComida" => "3",
"experienciaGeneral" => "5"
],
[
"atencionMesero" => "5",
"rapidezServicio" => "5",
"calidadComida" => "5",
"experienciaGeneral" => "5"
],
]);

function customCountBy($collection, $key_name) {
$counts = $collection->pluck($key_name)->countBy();

$unique_values = range(1, 5);

$result = [];
foreach ($unique_values as $value) {
$result[$value] = $counts[$value] ?? 0;
}

return $result;
}

$result = customCountBy($collection, 'rapidezServicio');

ksort($result);

print_r($result);


This customCountBy function will count the occurrences of each value in the specified key in the collection and then fill in the missing values with a count of 0. Finally, it will return the result in the desired format.

Rate this post

5 of 5 based on 7675 votes

Comments




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