Learn how to group an array of associative arrays by some key with PHP.

How to group an array of associative arrays by key in PHP

Sometimes, the group by function of SQL won't be enough to group some data according to your needs. Whatever the reason is, you will be able anyway to group the data as you want with the programming language of your preference. For example, in PHP it's possible to group an associative array by some key, so you will be able to display it's data by some order (group).

In this article, we'll share with you a tiny snippet that allows you to group items of an array by some key.

Group by function

The following function creates a new array that stores all the data of the original input array with an associative structure. It iterates once, creating a new key for the new array with the value of the data with the specified key (so when a new item with the same value appears, it will be pushed into this key). If an item of the input array doesn't contain the defined key, it will be pushed into the empty string key of the new array:

<?php

/**
 * Function that groups an array of associative arrays by some key.
 * 
 * @param {String} $key Property to sort by.
 * @param {Array} $data Array that stores multiple associative arrays.
 */
function group_by($key, $data) {
    $result = array();

    foreach($data as $val) {
        if(array_key_exists($key, $val)){
            $result[$val[$key]][] = $val;
        }else{
            $result[""][] = $val;
        }
    }

    return $result;
}

Usage

Consider the following data structure:

<?php 

$data = array(
    array(
        "id" => 1,
        "name" => "Bruce Wayne",
        "city" => "Gotham",
        "gender" => "Male"
    ),
    array(
        "id" => 2,
        "name" => "Thomas Wayne",
        "city" => "Gotham",
        "gender" => "Male"
    ),
    array(
        "id" => 3,
        "name" => "Diana Prince",
        "city" => "New Mexico",
        "gender" => "Female"
    ),
    array(
        "id" => 4,
        "name" => "Speedy Gonzales",
        "city" => "New Mexico",
        "gender" => "Male"
    )
);

We have 4 simple items and we want to group them by a single property, for example the gender, so our code to group our data by that key would be:

<?php

// Group data by the "gender" key 
$byGroup = group_by("gender", $data);

// Dump result
echo "<pre>" . var_export($byGroup, true) . "</pre>";

The dumped array would have the following structure:

array (
    'Male' => 
        array (
        0 => 
        array (
            'id' => 1,
            'name' => 'Bruce Wayne',
            'city' => 'Gotham',
            'gender' => 'Male',
        ),
        1 => 
        array (
            'id' => 2,
            'name' => 'Thomas Wayne',
            'city' => 'Gotham',
            'gender' => 'Male',
        ),
        2 => 
        array (
            'id' => 4,
            'name' => 'Speedy Gonzales',
            'city' => 'New Mexico',
            'gender' => 'Male',
        ),
    ),
    'Female' => 
        array (
        0 => 
        array (
            'id' => 3,
            'name' => 'Diana Prince',
            'city' => 'New Mexico',
            'gender' => 'Female',
        ),
    ),
)

As you can see, you will receive a new associative array with all the possible values of the selected key (in this case gender) of your data, so we have 2 groups namely Male and Female. You'll observe the same logic if you group by another property, for example the city:

<?php

// Group data by the "city" key 
$byGroup = group_by("city", $data);

// Dump result
echo "<pre>" . var_export($byGroup, true) . "</pre>";

Whose output would be:

array (
    'Gotham' => 
        array (
        0 => 
        array (
            'id' => 1,
            'name' => 'Bruce Wayne',
            'city' => 'Gotham',
            'gender' => 'Male',
        ),
        1 => 
        array (
            'id' => 2,
            'name' => 'Thomas Wayne',
            'city' => 'Gotham',
            'gender' => 'Male',
        ),
    ),
    'New Mexico' => 
        array (
        0 => 
        array (
            'id' => 3,
            'name' => 'Diana Prince',
            'city' => 'New Mexico',
            'gender' => 'Female',
        ),
        1 => 
        array (
            'id' => 4,
            'name' => 'Speedy Gonzales',
            'city' => 'New Mexico',
            'gender' => 'Male',
        ),
    ),
)

Happy coding !


Senior Software Engineer at Software Medico. Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World.

Sponsors