Creating a Three-Dimensional Array from a Two-Dimensional Array in PHP
Problem:
A two-dimensional array is given, and the challenge is to construct a three-dimensional array that groups the two-dimensional array's elements based on a specific key. Specifically, the three-dimensional array should have a key for each machine name, and the values for each machine key should be an array of jobs for that machine.
Solution:
To achieve this, initialize a new array $result and iterate through the two-dimensional array. For each element in the two-dimensional array, check its machine name and add it to the appropriate key in the $result array. If the machine name key does not yet exist in $result, create it and add the element as the first value.
Here is the code:
$result = []; foreach ($MainArray as $record) { $result[$record['Machine_Name']][] = $record; }
The above is the detailed content of How to Convert a 2D Array to a 3D Array in PHP by Grouping on a Key?. For more information, please follow other related articles on the PHP Chinese website!