Home > Backend Development > PHP Tutorial > How to Group a 2D Array by Column Value into a 3D Array?

How to Group a 2D Array by Column Value into a 3D Array?

Susan Sarandon
Release: 2024-11-02 17:28:29
Original
1017 people have browsed it

How to Group a 2D Array by Column Value into a 3D Array?

Group 2D Array Data Using Column Value for 3D Array

In programming, it's often necessary to manipulate and organize data structures effectively. Grouping data based on specific criteria is a common task. This article explores how to group a 2D array using a column value to create a 3D array.

Consider the following 2D array:

[
    ['cust' => 'XT8900', 'type' => 'standard', 'level' => 1],
    ['cust' => 'XT8944', 'type' => 'standard', 'level' => 1],
    ['cust' => 'XT8922', 'type' => 'premier', 'level' => 3],
    ['cust' => 'XT8816', 'type' => 'permier', 'level' => 3],
    ['cust' => 'XT7434', 'type' => 'standard', 'level' => 7],
]
Copy after login

Our objective is to group this data by the 'level' column, which effectively creates a 3D array. The desired output looks like this:

Array (

   [1] => Array (
          [0] => Array (
                    [cust] => XT8900
                    [type] => standard
                    )
          [1] => Array (
                    [cust] => XT8944
                    [type] => standard
                    )
          )

   [3] => Array (
          [2] => Array (
                 [cust] => XT8922
                 [type] => premier
                 )

          [3] => Array (
                 [cust] => XT8816
                 [type] => permier
                 )
          )

   [7] => Array (
          [4] => Array (
                 [cust] => XT7434
                 [type] => standard
                 )
          )
)
Copy after login

Optimal Approach

The most efficient solution is to create the 3D array directly if possible. However, if this is not feasible, we can use an intermediate temporary array for sorting:

<code class="php">foreach ($input_arr as $key => &$entry) {
    $level_arr[$entry['level']][$key] = $entry;
}</code>
Copy after login

This results in the desired 3D array structure. It's important to consider building the array in the final format from the beginning if possible, for optimal performance.

The above is the detailed content of How to Group a 2D Array by Column Value into a 3D Array?. 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