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

Barbara Streisand
Release: 2024-10-28 13:08:02
Original
349 people have browsed it

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

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

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!