"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 Group Associative Arrays by Column Value While Preserving Keys in PHP?

How to Group Associative Arrays by Column Value While Preserving Keys in PHP?

Published on 2024-11-06
Browse:677

How to Group Associative Arrays by Column Value While Preserving Keys in PHP?

Grouping Associative Arrays by Column Value While Preserving Keys

Consider an array of associative arrays, each representing an entity with attributes like 'id' and 'name'. The challenge is to group these arrays based on a specific column, 'id', while maintaining the original keys.

To achieve this, we can use PHP's foreach loop to iterate over the array. For each inner array, we extract the 'id' value and use it as the index of a new associative array. Within this new array, we assign the original key as the index and the inner array as the value.

$arr = array();

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

Finally, we use ksort() to sort the resulting array numerically, ensuring that the groups are presented in ascending order of 'id'.

ksort($arr, SORT_NUMERIC);

The output will be an array where each element represents a group of entities with the same 'id' value, while the original keys are preserved within each group.

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