I am trying to aggregate data for reporting in our database, and when accessing the data it returns as an array of strings like so:
[
0 => null
1 => "1"
2 => "1"
3 => "1,2,3"
4 => "2"
5 => "2"
6 => "3"
]
what I need to do is transform the array somehow so that this is the result:
[
"N/A" => 1,
"1" => 3,
"2" => 3,
"3" => 2,
]
where null values in the array are counted as "N/A" and all other values are counted distinctly like above, there are 3 1's, 3 2's, and 2 3's.
Per request, what I have tried so far is a few variations on the map() function:
$typeCounts = $referralsByType->map(function ($item) {
$item = explode(',', $item);
$item = array_filter($item);
$item = array_count_values($item);
$item = array_map(function ($key, $value) {
if ($key === null) {
$key = 'N/A';
}
return [$key => $value];
}, array_keys($item), array_values($item));
$item = array_collapse($item);
return $item;
});
I've played around with a few different variations of the above code, but it ends up giving incorrect results in a format that I didn't expect.