A user encountered a challenge while trying to transform a 2-dimensional array ($MainArray) into a 3-dimensional array ($ConvertedArray). The user aimed to group jobs based on their machine names and maintain their original keys.
The solution to this challenge lies in utilizing a PHP function called array_column. This function allows you to extract specific columns from a multidimensional array. Here's how to use it in this case:
$machineNames = array_column($MainArray, 'Machine_Name'); $uniqueMachines = array_unique($machineNames); $ConvertedArray = []; foreach ($uniqueMachines as $machineName) { $ConvertedArray[$machineName] = array_filter($MainArray, function ($job) use ($machineName) { return $job['Machine_Name'] === $machineName; }); }
This code accomplishes the desired transformation by iterating over the unique machine names and grouping the jobs accordingly into the $ConvertedArray. The result is a new array with machine names as keys and arrays of related jobs as values.
The provided code can be easily implemented in your PHP script to achieve the desired output. The original and converted arrays can be printed for verification:
echo '<pre class="brush:php;toolbar:false">'; print_r($MainArray); echo ''; echo '
'; print_r($ConvertedArray); echo '';
This will output both the original 2-dimensional array and the newly created 3-dimensional array.
The above is the detailed content of How Can I Transform a 2D PHP Array into a 3D Array Based on a Column's Values?. For more information, please follow other related articles on the PHP Chinese website!