Home >Backend Development >PHP Tutorial >How to Group Multidimensional Array Rows by Column Value in PHP?

How to Group Multidimensional Array Rows by Column Value in PHP?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-18 10:14:12517browse

How to Group Multidimensional Array Rows by Column Value in PHP?

Group Array Rows by Column Value and Form Subarrays Using PHP

Grouping rows in a multidimensional array by a specific column value is a common task in data manipulation. While there is no built-in PHP function to achieve this directly, a custom loop can efficiently group the rows based on a chosen column.

Consider the following multidimensional array:

$array = [
    [
        'id' => 96,
        'shipping_no' => '212755-1',
        'part_no' => 'reterty',
        'description' => 'tyrfyt',
        'packaging_type' => 'PC',
    ],
    [
        'id' => 96,
        'shipping_no' => '212755-1',
        'part_no' => 'dftgtryh',
        'description' => 'dfhgfyh',
        'packaging_type' => 'PC',
    ],
    [
        'id' => 97,
        'shipping_no' => '212755-2',
        'part_no' => 'ZeoDark',
        'description' => 's%c%s%c%s',
        'packaging_type' => 'PC',
    ],
];

To group the array by the 'id' column, a simple foreach loop can be used:

$result = [];
foreach ($array as $element) {
    $result[$element['id']][] = $element;
}

This loop iterates through each element in the original array and stores it in the 'result' array, where the 'id' value serves as the key. As a result, the 'result' array will be grouped by the 'id' column:

Array
(
    [96] => Array
        (
            [0] => Array
                (
                    [id] => 96
                    [shipping_no] => 212755-1
                    [part_no] => reterty
                    [description] => tyrfyt
                    [packaging_type] => PC
                )
            [1] => Array
                (
                    [id] => 96
                    [shipping_no] => 212755-1
                    [part_no] => dftgtryh
                    [description] => dfhgfyh
                    [packaging_type] => PC
                )
        )
    [97] => Array
        (
            [0] => Array
                (
                    [id] => 97
                    [shipping_no] => 212755-2
                    [part_no] => ZeoDark
                    [description] => s%c%s%c%s
                    [packaging_type] => PC
                )
        )
)

The above is the detailed content of How to Group Multidimensional Array Rows by Column Value in PHP?. 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