Home >Backend Development >PHP Tutorial >How to Group 2D Array Data by Column Values to Create a 3D Array?
Grouping 2D Array Data Utilizing Column Values to Create a 3D Array
Grouping multidimensional array elements based on a specific column's values can be achieved using a structured approach. Here's a detailed explanation of how to accomplish this task:
Sorting the Data
To group the data, we first need to sort it according to the level key. A temporary array can be utilized for this purpose:
<code class="php">$level_arr = []; foreach ($input_arr as $key => &$entry) { $level_arr[$entry['level']][$key] = $entry; }</code>
This sorting operation creates an array where each key represents a level value, and the corresponding values are arrays containing the elements with that level.
Building the 3D Array
Once the data is sorted, we can construct the desired 3D array:
<code class="php">$result_arr = []; foreach ($level_arr as $level => $level_data) { foreach ($level_data as $index => $entry) { $result_arr[$level][$index] = $entry; } }</code>
The result is a 3D array where each top-level key represents a level, the second-level keys are the original indices, and the values are the associated data elements.
Considerations
The above is the detailed content of How to Group 2D Array Data by Column Values to Create a 3D Array?. For more information, please follow other related articles on the PHP Chinese website!