Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to group an array by a field value

Short answer

Loop over the array and put the elements into a sub-array under the needed key:

<?php
 
$products = [
    ['title' => 'Tea', 'category' => 'drinks'],
    ['title' => 'Bread', 'category' => 'food'],
    ['title' => 'Coffee', 'category' => 'drinks'],
];
 
$groups = [];
 
foreach ($products as $product) {
    $groups[$product['category']][] = $product['title'];
}
 
echo json_encode($groups);

Output:

{"drinks":["Tea","Coffee"],"food":["Bread"]}

The count in each group

If only the numbers are needed, array_column() and array_count_values() are enough:

<?php
 
$products = [
    ['title' => 'Tea', 'category' => 'drinks'],
    ['title' => 'Bread', 'category' => 'food'],
    ['title' => 'Coffee', 'category' => 'drinks'],
];
 
echo json_encode(array_count_values(array_column($products, 'category')));

Output:

{"drinks":2,"food":1}

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.