Home > Backend Development > PHP Tutorial > How Can I Transform a 2D PHP Array into a 3D Array Based on a Column's Values?

How Can I Transform a 2D PHP Array into a 3D Array Based on a Column's Values?

Patricia Arquette
Release: 2024-12-10 07:36:09
Original
293 people have browsed it

How Can I Transform a 2D PHP Array into a 3D Array Based on a Column's Values?

Creating a New Array from an Existing Array in PHP

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.

Solution

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;
    });
}
Copy after login

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.

Implementation

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 '
';
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template