How to Organize Associative Array Rows Based on a Specific Column Value?

DDD
Release: 2024-10-30 11:49:03
Original
184 people have browsed it

How to Organize Associative Array Rows Based on a Specific Column Value?

Organizing Associative Array Rows by Column Value

When working with an associative array consisting of subarrays, it is often necessary to reorganize the data based on specific column values. This allows for easier data retrieval and analysis.

Suppose we have an array of subarrays in the following format:

[
    '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

Our goal is to group these subarrays into a new array based on the 'id' field present in each subarray.

To achieve this, we can follow these steps:

  1. Initialize an empty array:
$arr = array();
Copy after login
  1. Loop through each subarray in the original array. For each subarray, extract its 'id' value and use it as the key in the new array:
foreach ($old_arr as $key => $item) {
   $arr[$item['id']][$key] = $item;
}
Copy after login
  1. This step sorts the new array by 'id' in ascending order:
ksort($arr, SORT_NUMERIC);
Copy after login
  1. Finally, the resulting array is organized by 'id' values:
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

The above is the detailed content of How to Organize Associative Array Rows Based on a Specific Column Value?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!