Backend Development 4 min read

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.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
Counting Items with Identical Fields in a Two‑Dimensional PHP Array

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.

backendData ProcessingPHParrayGrouping
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.