Home >Backend Development >PHP Tutorial >How to Group 2D Array Data by Column Value into a 3D Array in PHP?
When working with multidimensional arrays, it can become necessary to reorganize the data into different groupings. Let's consider a scenario where we have an array of customer information, and we need to group them according to their level. However, we do not have prior knowledge of the maximum level value.
To achieve this, we can exploit PHP's flexibility in array structures. Here's a step-by-step approach to group the data:
Create a temporary array to sort the data:
<code class="php">foreach ($input_arr as $key => &$entry) { $level_arr[$entry['level']][$key] = $entry; }</code>
After the loop, the $level_arr array will have the desired grouped structure, with each level value representing a key for a nested array containing all the customer information at that level.
Alternatively, if you have control over the initial array's construction, it is more efficient to store the data in the desired structure from the start. This approach eliminates the need for a separate sorting step.
The above is the detailed content of How to Group 2D Array Data by Column Value into a 3D Array in PHP?. For more information, please follow other related articles on the PHP Chinese website!