Home >Backend Development >PHP Tutorial >How Can I Group Rows in a 2D PHP Array Based on a Column Value Using Iteration?
Grouping 2D Array Rows by a Column Value Using Iterative Approach
When dealing with complex multidimensional arrays, the need to group rows based on specific column values often arises. While PHP lacks native functions for this task, a simple foreach loop can effectively achieve this.
Consider the following array:
$data = [ [ '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' ] ];
To group the array rows by the 'id' column, use the following loop:
$result = []; foreach ($data as $element) { $result[$element['id']][] = $element; }
This loop iterates through each element of the original array. For each element, it checks the 'id' value and adds the element to the corresponding subarray in the result array.
The resulting $result array will be grouped by 'id' as follows:
[ 96 => [ // Element with id 96 from the original array // Element with id 96 from the original array ], 97 => [ // Element with id 97 from the original array ] ]
This approach avoids duplicate items in the result array, ensuring that each row is assigned to its correct group based on the 'id' column value.
The above is the detailed content of How Can I Group Rows in a 2D PHP Array Based on a Column Value Using Iteration?. For more information, please follow other related articles on the PHP Chinese website!