'I need countBy to include "zero" occurrences to keep the array length in PHP
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.
Solution 1:[1]
You can get the result of countBy and add it with a default array. The result will be what you need.
$yourArray = ["2" => 2, "5" => 1];
$defaultArray = ["1" => 0, "2" => 0, "3" => 0, "4" => 0, "5" => 0];
$finalArray = $yourArray + $defaultArray;
$finalArray would be:
Array
(
[1] => 1
[2] => 2
[5] => 1
[3] => 0
[4] => 0
)
and you can sort it
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Giacomo M |
