Home >Backend Development >PHP Tutorial >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);
To fully address this issue, we can utilize a loop-based approach:
$result = array(); foreach ($data as $element) { $result[$element['id']][] = $element; }
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!