PHP

Group Array of Arrays by a Specific Key

Learn to organize a list of associative arrays into groups based on a common key's value, creating a structured hierarchical array in PHP.

$users = [
    ['id' => 1, 'name' => 'Alice', 'city' => 'New York'],
    ['id' => 2, 'name' => 'Bob', 'city' => 'London'],
    ['id' => 3, 'name' => 'Charlie', 'city' => 'New York'],
    ['id' => 4, 'name' => 'David', 'city' => 'Paris'],
    ['id' => 5, 'name' => 'Eve', 'city' => 'London'],
];

$groupedUsers = [];
foreach ($users as $user) {
    $city = $user['city'];
    if (!isset($groupedUsers[$city])) {
        $groupedUsers[$city] = [];
    }
    $groupedUsers[$city][] = $user;
}

echo "Users grouped by city:
";
print_r($groupedUsers);
How it works: This snippet demonstrates how to group an array of associative arrays by the value of a specific key (in this case, 'city'). It iterates through the original array, uses the key's value as the new outer array key, and then appends the entire sub-array to that group. This technique is fundamental for organizing and structuring data for display or further processing.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs