Home >Backend Development >PHP Tutorial >How can I group associative array rows by a specific column value in PHP while preserving the original first-level keys?

How can I group associative array rows by a specific column value in PHP while preserving the original first-level keys?

DDD
DDDOriginal
2024-10-30 14:07:50867browse

How can I group associative array rows by a specific column value in PHP while preserving the original first-level keys?

Grouping Associative Array Rows by Column Value

Given an associative array of associative arrays, a common task is to group them by a specific column value while preserving the original first-level keys. Consider the following input array:

[
    'a' => ['id' => 20, 'name' => 'chimpanzee'],
    'b' => ['id' => 40, 'name' => 'meeting'],
    'c' => ['id' => 20, 'name' => 'dynasty'],
    'd' => ['id' => 50, 'name' => 'chocolate'],
    'e' => ['id' => 10, 'name' => 'bananas'],
    'f' => ['id' => 50, 'name' => 'fantasy'],
    'g' => ['id' => 50, 'name' => 'football']
]

Our goal is to group these subarrays based on the id value:

array
(
    10 => array
        (
            e => array ( id = 10, name = bananas )
        )
    20 => array
        (
            a => array ( id = 20, name = chimpanzee )
            c => array ( id = 20, name = dynasty )
        )
    40 => array
        (
            b => array ( id = 40, name = meeting )
        )
    50 => array
        (
            d => array ( id = 50, name = chocolate )
            f => array ( id = 50, name = fantasy )
            g => array ( id = 50, name = football )
        )
)

To accomplish this using PHP, we can utilize the following code:

$arr = array();

foreach ($old_arr as $key => $item) {
   $arr[$item['id']][$key] = $item;
}

ksort($arr, SORT_NUMERIC);

This code first iterates over the original array, extracting the id and corresponding subarray. It then stores this subarray in the new array under the id key and preserves the original first-level key. Finally, it sorts the new array numerically by id.

The above is the detailed content of How can I group associative array rows by a specific column value in PHP while preserving the original first-level keys?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn