Home > Backend Development > PHP Tutorial > How Can I Efficiently Group 2D Array Rows by a Column Value in PHP?

How Can I Efficiently Group 2D Array Rows by a Column Value in PHP?

Mary-Kate Olsen
Release: 2024-12-16 17:19:11
Original
990 people have browsed it

How Can I Efficiently Group 2D Array Rows by a Column Value in PHP?

Grouping 2D Array Rows by a Column Value Effectively

In this example, we have a scenario where we need to group an array of associative arrays based on a specific column value, 'id'. The goal is to achieve this task without introducing duplicates while maintaining the original data structure.

While array_column() and array_unique() can partially achieve the grouping, it falls short in avoiding duplicates, as illustrated below:

function array_group_by_id($array) {
  return array_column($array, null, 'id');
}

$grouped_array = array_group_by_id($data);
Copy after login

To fully address this issue, we can utilize a loop-based approach:

$result = array();

foreach ($data as $element) {
  $result[$element['id']][] = $element;
}
Copy after login

This loop iterates over the original array, adding each element to the corresponding subarray within the 'result' array based on its 'id' value. This effectively creates a nested structure where each subarray contains rows from the original array that share the same 'id'.

The above is the detailed content of How Can I Efficiently Group 2D Array Rows by a Column Value 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