Home >Backend Development >PHP Tutorial >How Can I Restructure a 2D PHP Array into a 3D Array by Machine and Ordered Jobs?
Restructuring a Multidimensional Array in PHP
In the given query, the goal is to transform a 2D array into a 3D array where each element represents a machine and contains its associated jobs arranged in ascending order based on their original key. Here's how this can be achieved in PHP:
We begin by initializing an empty array called $result that will hold the restructured data. Then, we iterate through the original array, $MainArray, using a foreach loop.
For each record in $MainArray, we extract the Machine_Name value and use it as the key for a sub-array within $result. If an entry for that machine doesn't exist in $result, it will be created with an empty array.
We then append the current record to the sub-array associated with the Machine_Name. This effectively groups all jobs related to the same machine together.
To ensure the jobs are arranged in the desired order, we sort each sub-array in ascending order of the original key using the ksort function. The result is stored back into the $result array.
The code below demonstrates this process:
$result = []; foreach ($MainArray as $record) { $result[$record['Machine_Name']][] = $record; } foreach ($result as $machine => $jobs) { ksort($result[$machine]); }
This code will produce a 3D array, $result, where the first dimension represents machines and the second dimension contains an ordered list of jobs associated with each machine.
The above is the detailed content of How Can I Restructure a 2D PHP Array into a 3D Array by Machine and Ordered Jobs?. For more information, please follow other related articles on the PHP Chinese website!