Counting Items with Identical Fields in a Two‑Dimensional PHP Array
This article demonstrates two PHP approaches—manual looping and functional array utilities—to group and count records in a two‑dimensional array based on identical name and age fields, showing the full source code and expected output.
The article explains how to count occurrences of rows that share the same name and age values in a two‑dimensional PHP array.
Original method (manual loop)
First, the sample data is defined:
$data = [
['id' => 1, 'name' => 'John', 'age' => 25],
['id' => 2, 'name' => 'Jane', 'age' => 30],
['id' => 3, 'name' => 'John', 'age' => 28],
['id' => 4, 'name' => 'Jane', 'age' => 35],
['id' => 5, 'name' => 'John', 'age' => 25],
];An empty array $statistics is created to store the grouping result.
$statistics = [];The array is traversed, a composite key $name . '_' . $age is built, and each item is appended to the corresponding group.
foreach ($data as $item) {
$name = $item['name'];
$age = $item['age'];
$key = $name . '_' . $age;
if (!isset($statistics[$key])) {
$statistics[$key] = [];
}
$statistics[$key][] = $item;
}The grouped result is printed:
foreach ($statistics as $key => $group) {
echo "属性相同的数据({$key})有:" . PHP_EOL;
foreach ($group as $item) {
echo "ID: {$item['id']}, Name: {$item['name']}, Age: {$item['age']}" . PHP_EOL;
}
echo PHP_EOL;
}The output shows each name_age combination and the rows that belong to it.
Function‑based method
The same task is performed using array_map to build the groups and array_walk to display them.
$statistics = [];
array_map(function ($v) use (&$statistics) {
$key = $v['name'] . '_' . $v['age'];
if (!isset($statistics[$key])) {
$statistics[$key] = [];
}
$statistics[$key][] = $v;
}, $data);
array_walk($statistics, function ($group, $key) {
echo "属性相同的数据({$key})有:" . PHP_EOL;
foreach ($group as $item) {
echo "ID: {$item['id']}, Name: {$item['name']}, Age: {$item['age']}" . PHP_EOL;
}
echo PHP_EOL;
});Both approaches produce identical results, demonstrating how to group and count records efficiently in PHP.
Laravel Tech Community
Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.