Efficiently Grouping 2D Arrays by Column Value Using PHP
Grouping multidimensional arrays by a specific column value can enhance data organization and retrieval. While there are no native PHP functions for this task, a custom approach using a foreach loop can effectively achieve this goal.
Problem:
Consider the following 2D array representing rows of data:
$array = [ [ 'id' => 96, 'shipping_no' => '212755-1', 'part_no' => 'reterty', 'description' => 'tyrfyt', 'packaging_type' => 'PC', ], [ 'id' => 96, 'shipping_no' => '212755-1', 'part_no' => 'dftgtryh', 'description' => 'dfhgfyh', 'packaging_type' => 'PC', ], [ 'id' => 97, 'shipping_no' => '212755-2', 'part_no' => 'ZeoDark', 'description' => 's%c%s%c%s', 'packaging_type' => 'PC', ], ];
The objective is to group the array elements by the 'id' column and form subarrays of the grouped rows.
Solution:
Using a foreach loop:
$result = []; foreach ($data as $element) { $result[$element['id']][] = $element; }
Explanation:
The foreach loop iterates through each element in the $data array. For each element, it checks the 'id' column and uses it as a key in the $result array. If the key (id) already exists, a new element is appended to the corresponding subarray.
Output:
The $result array will be grouped based on the 'id' column, resulting in:
$result = [ 96 => [ [ 'id' => 96, 'shipping_no' => '212755-1', 'part_no' => 'reterty', 'description' => 'tyrfyt', 'packaging_type' => 'PC', ], [ 'id' => 96, 'shipping_no' => '212755-1', 'part_no' => 'dftgtryh', 'description' => 'dfhgfyh', 'packaging_type' => 'PC', ], ], 97 => [ [ 'id' => 97, 'shipping_no' => '212755-2', 'part_no' => 'ZeoDark', 'description' => 's%c%s%c%s', 'packaging_type' => 'PC', ], ], ];
This method provides a flexible and efficient way to group 2D arrays by a specified column value, enabling efficient data extraction and manipulation.
The above is the detailed content of How to Efficiently Group a 2D PHP Array by Column Value?. For more information, please follow other related articles on the PHP Chinese website!