Home > Backend Development > PHP Tutorial > How to Group Associative Array Rows by Column Value in PHP?

How to Group Associative Array Rows by Column Value in PHP?

Mary-Kate Olsen
Release: 2024-10-30 06:16:03
Original
580 people have browsed it

How to Group Associative Array Rows by Column Value in PHP?

Grouping Associative ArrayRows by Column Value

In programming, you may encounter situations where you need to reorganize data stored in associative arrays. One common task is to group rows in the array by a specific column value while preserving the original first-level keys.

Consider the following associative array of associative arrays known as $old_arr:

[
    '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']
]
Copy after login

The goal is to create a new array, $arr, where rows are grouped based on the id field. The resulting array should look like this:

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 )
          )
)
Copy after login

To achieve this, you can follow these steps:

  1. Initialize an empty array $arr.
  2. Iterate over each row in $old_arr.
  3. Use the id value as a key in $arr. If the key does not exist, create a new array.
  4. Assign the current row to the corresponding key in $arr.
  5. Sort the $arr array by SORT_NUMERIC to ensure that the keys are in numerical order.

The provided PHP code follows this approach to generate the desired result:

$arr = array();

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

ksort($arr, SORT_NUMERIC);
Copy after login

The above is the detailed content of How to Group Associative Array Rows by Column Value in PHP?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template