Home >Backend Development >PHP Tutorial >How to Transform a 2D PHP Array into a 3D Array Based on a Key's Value?

How to Transform a 2D PHP Array into a 3D Array Based on a Key's Value?

Linda Hamilton
Linda HamiltonOriginal
2024-12-18 00:43:10857browse

How to Transform a 2D PHP Array into a 3D Array Based on a Key's Value?

Creating a Multidimensional Array from an Existing One in PHP

In PHP, it's possible to create a new multidimensional array based on an existing one. Here's how to accomplish the specific transformation you described in your question:

Convert the following 2D array:

$MainArray = array(
    [
        '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
    ],
    [
        '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
    ],
    [
        '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
    ]
);

Into the following 3D array:

$ConvertedArray = array(
    'Machine1' => array(
        [
            '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' => array(
        [
            '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
        ]
    )
);

Solution:

Use the following PHP code:

$result = [];
foreach($MainArray as $record){
 $result[$record['Machine_Name']][] = $record;
}

The code iterates through the $MainArray and for each record, adds it to the $result array, using the value of the 'Machine_Name' key as the index. This results in the creation of the desired 3D array.

The above is the detailed content of How to Transform a 2D PHP Array into a 3D Array Based on a Key's Value?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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