Home > Backend Development > PHP Tutorial > How to Convert a 2D Array to a 3D Array in PHP by Grouping on a Key?

How to Convert a 2D Array to a 3D Array in PHP by Grouping on a Key?

Linda Hamilton
Release: 2024-12-09 16:17:15
Original
424 people have browsed it

How to Convert a 2D Array to a 3D Array in PHP by Grouping on a Key?

Creating a Three-Dimensional Array from a Two-Dimensional Array in PHP

Problem:

A two-dimensional array is given, and the challenge is to construct a three-dimensional array that groups the two-dimensional array's elements based on a specific key. Specifically, the three-dimensional array should have a key for each machine name, and the values for each machine key should be an array of jobs for that machine.

Solution:

To achieve this, initialize a new array $result and iterate through the two-dimensional array. For each element in the two-dimensional array, check its machine name and add it to the appropriate key in the $result array. If the machine name key does not yet exist in $result, create it and add the element as the first value.

Here is the code:

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

The above is the detailed content of How to Convert a 2D Array to a 3D Array in PHP by Grouping on a Key?. 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