Home >Backend Development >PHP Tutorial >How to Group a 2D PHP Array into a 3D Array by Machine Name?
How to Convert a 2D Array to a 3D Array in PHP
You have an existing 2D array that contains job information for different machines. The task is to convert this array into a 3D array, grouped by machine name.
The desired output is a 3D array where the keys are machine names, and each machine name contains an array of job records. The job records include the following fields:
Job_Name Quantity Start_Date Completion_Date Labor
PHP Code Solution:
To convert the 2D array to a 3D array, you can use the following PHP code:
$result = []; foreach ($MainArray as $record) { $result[$record['Machine_Name']][] = $record; }
Explanation:
The foreach loop iterates through each record in the $MainArray. For each record, it checks the Machine_Name field and adds the record to the corresponding machine array in the $result array.
If the machine name does not exist as a key in the $result array, it is created and the record is added to the array under that key.
Example:
Given the following $MainArray:
[0] => [ 'Job_Name' => 'WXYZ', 'Quantity' => 1000, 'Machine_Name' => 'Machine1', 'Start_Date' => '2014-07-30 00:00:00', 'Completion_Date' => '2014-08-02 00:00:00', 'Labor' => 4 ] [1] => [ 'Job_Name' => 'ABCD', 'Quantity' => 1500, 'Machine_Name' => 'Machine2', 'Start_Date' => '2014-08-08 00:00:00', 'Completion_Date' => '2014-08-14 00:00:00', 'Labor' => 2 ] [2] => [ 'Job_Name' => 'BCDA', 'Quantity' => 1200, 'Machine_Name' => 'Machine1', 'Start_Date' => '2014-08-02 00:00:00', 'Completion_Date' => '2014-08-07 00:00:00', 'Labor' => 1 ]
The output of the $result array would be:
[Machine1] => [ [ 'Job_Name' => 'WXYZ', 'Quantity' => 1000, 'Start_Date' => '2014-07-30 00:00:00', 'Completion_Date' => '2014-08-02 00:00:00', 'Labor' => 4 ], [ 'Job_Name' => 'BCDA', 'Quantity' => 1200, 'Start_Date' => '2014-08-02 00:00:00', 'Completion_Date' => '2014-08-07 00:00:00', 'Labor' => 1 ] ] [Machine2] => [ [ 'Job_Name' => 'ABCD', 'Quantity' => 1500, 'Start_Date' => '2014-08-08 00:00:00', 'Completion_Date' => '2014-08-14 00:00:00', 'Labor' => 2 ] ]
This new 3D array can be used to access job records grouped by machine name.
The above is the detailed content of How to Group a 2D PHP Array into a 3D Array by Machine Name?. For more information, please follow other related articles on the PHP Chinese website!