Home >Backend Development >PHP Tutorial >How to Transform a 2D Array into a 3D Array by Grouping Elements Based on a Column Value?
In programming, you may encounter the need to organize data in multidimensional arrays. To efficiently manage complex data, it becomes essential to group elements according to specific criteria. This article tackles the specific challenge of grouping a 2D array by the values in a specific column, transforming it into a 3D array for enhanced visualization and manipulation.
Consider the following multidimensional array containing customer information:
<code class="php">$data = [ ['cust' => 'XT8900', 'type' => 'standard', 'level' => 1], ['cust' => 'XT8944', 'type' => 'standard', 'level' => 1], ['cust' => 'XT8922', 'type' => 'premier', 'level' => 3], ['cust' => 'XT8816', 'type' => 'premier', 'level' => 3], ['cust' => 'XT7434', 'type' => 'standard', 'level' => 7], ];</code>
The objective is to group these customer records based on the 'level' column and create a 3D array where each level contains an array of customer information. The desired result should look something like this:
<code class="php">$result = [ 1 => [ ['cust' => 'XT8900', 'type' => 'standard'], ['cust' => 'XT8944', 'type' => 'standard'], ], 3 => [ ['cust' => 'XT8922', 'type' => 'premier'], ['cust' => 'XT8816', 'type' => 'premier'], ], 7 => [ ['cust' => 'XT7434', 'type' => 'standard'], ], ];</code>
There are several approaches to achieve this but let's explore an effective solution:
Grouping the Sorted Data:
Now, iterate through the sorted data and create a temporary array. For each entry, retrieve the 'level' value as the key and store the entire entry as the value. This will effectively group the customer records by level.
<code class="php">foreach ($data as $key => &$entry) { $level_arr[$entry['level']][$key] = $entry; }</code>
The resulting $level_arr will have the desired structure, with each level containing an array of customer information.
Converting to a 3D Array:
Now, convert the temporary $level_arr into the target 3D array. This involves setting the keys of the 3D array to the level values and the values to the corresponding customer arrays from $level_arr.
<code class="php">$result = []; foreach ($level_arr as $level => $customer_data) { $result[$level] = array_values($customer_data); }</code>
By following these steps, you can effectively group data in a 2D array using a specific column value and construct a 3D array for enhanced data manipulation and visualization. This approach offers flexibility and efficiency when dealing with complex data structures.
The above is the detailed content of How to Transform a 2D Array into a 3D Array by Grouping Elements Based on a Column Value?. For more information, please follow other related articles on the PHP Chinese website!