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
- array_column — Pulls the values of one key out of an array of arrays.
- array_count_values — Counts how many times each value occurs.
- array_keys — Returns all the keys of an array.