"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to organize associative array rows based on specific column values?

How to organize associative array rows based on specific column values?

Posted on 2025-04-17
Browse:312

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

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();
  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;
}
  1. This step sorts the new array by 'id' in ascending order:
ksort($arr, SORT_NUMERIC);
  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 )
          )
)
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3