2

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.

2
  • Please show us what you have tried so far Commented Jun 2, 2022 at 18:57
  • @symlink I have added additional context and given my latest attempt as an example. Commented Jun 2, 2022 at 19:04

1 Answer 1

1

I figured it out:

 $totals = implode(',', $referralsByType);
 $totals = explode(',', $totals);
 $totals = array_count_values($totals);

I was overcomplicating this entire function, I just needed to take a second and step away.

Sign up to request clarification or add additional context in comments.

1 Comment

That implode-explode stuff is completely superfluous, all three lines can be replaced with just $totals = array_count_values($referralsByType);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.