Search code examples
phparraysmultidimensional-arraycountgrouping

Group data from a 2d array by one column then conditionally populate keys within the group and count the number of subarray key occurrences


I have the following array

$topics_percentage = [
    ['id' => 8989, 'cat' => 'Category 1', 'completed' => 0],
    ['id' => 8919, 'cat' => 'Category 2', 'completed' => 1],
    ['id' => 8913, 'cat' => 'Category 2', 'completed' => 1],
    ['id' => 8947, 'cat' => 'Category 1', 'completed' => 1],
    ['id' => 8949, 'cat' => 'Category 3', 'completed' => 1],
];

I need to group by category values as the first level keys, then conditionally count the completed and noncompleted values in each group according to the 0 or 1 value of the completed elements.

Desired result:

[
    'Category 1' => [
        'noncompleted' => 1,
        'completed' => 1,
    ],
    'Category 2' => [
        'completed' => 2,
    ],
    'Category 3' => [
        'completed' => 1,
    ]
]

Solution

  • Try this:

        foreach ($topics_percentage as $v) {
    
            $complete = $v['completed'];
    
            if ($complete == 1) {
                $class_array[$v['cat']]['completed']++;
            } else {
                $class_array[$v['cat']]['uncompleted']++;
            }
        }
    

    You should, of course, preinitialize the array before you count up values, but the basic idea is to use array cells as numeric values to be added or substracted from.