Home > Article > Backend Development > How to Group a 2D Array by Column Value into a 3D Array?
In programming, it's often necessary to manipulate and organize data structures effectively. Grouping data based on specific criteria is a common task. This article explores how to group a 2D array using a column value to create a 3D array.
Consider the following 2D array:
[ ['cust' => 'XT8900', 'type' => 'standard', 'level' => 1], ['cust' => 'XT8944', 'type' => 'standard', 'level' => 1], ['cust' => 'XT8922', 'type' => 'premier', 'level' => 3], ['cust' => 'XT8816', 'type' => 'permier', 'level' => 3], ['cust' => 'XT7434', 'type' => 'standard', 'level' => 7], ]
Our objective is to group this data by the 'level' column, which effectively creates a 3D array. The desired output looks like this:
Array ( [1] => Array ( [0] => Array ( [cust] => XT8900 [type] => standard ) [1] => Array ( [cust] => XT8944 [type] => standard ) ) [3] => Array ( [2] => Array ( [cust] => XT8922 [type] => premier ) [3] => Array ( [cust] => XT8816 [type] => permier ) ) [7] => Array ( [4] => Array ( [cust] => XT7434 [type] => standard ) ) )
Optimal Approach
The most efficient solution is to create the 3D array directly if possible. However, if this is not feasible, we can use an intermediate temporary array for sorting:
<code class="php">foreach ($input_arr as $key => &$entry) { $level_arr[$entry['level']][$key] = $entry; }</code>
This results in the desired 3D array structure. It's important to consider building the array in the final format from the beginning if possible, for optimal performance.
The above is the detailed content of How to Group a 2D Array by Column Value into a 3D Array?. For more information, please follow other related articles on the PHP Chinese website!