Home  >  Article  >  Backend Development  >  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?

Barbara Streisand
Barbara StreisandOriginal
2024-10-28 13:08:02350browse

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.

<code class="php">$arr = array();

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

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

<code class="php">ksort($arr, SORT_NUMERIC);</code>

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.

The above is the detailed content of How to Group Associative Arrays by Column Value While Preserving Keys in PHP?. 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