Amit
Amit

Reputation: 49

Group rows of a 2d array by column value and push rows into grouped subarrays

I have multidimensional array; I have to group all subarrays having same ID. I tried with chunk but it is not working.


Array
(
    [0] => Array
        (
            [ID] => A11495
            [CID] => 000020
            [msgtype] => Periodic Report
        )
    [1] => Array
        (
        
            [ID] => A11495
            [CID] => 000020
            [msgtype] => Periodic Report
        )
    [2] => Array
        (
            [ID] => A11495
            [CID] => 000020
            [msgtype] => Periodic Report
        )

    [3] => Array
        (
            [ID] => A11496
            [CID] => 000020
            [msgtype] => Periodic Report
            
        )
    )   

Expecting output as below array

Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [ID] => A11495
                    [CID] => 000020
                    [msgtype] => Periodic Report
                )

            [1] => Array
                (
                    [ID] => A11495
                    [CID] => 000020
                    [msgtype] => Periodic Report
                    
                )

            [2] => Array
                (
                    [ID] => A11495
                    [CID] => 000020
                    [msgtype] => Periodic Report
                )
        )
    [1] => Array
        (   
            [0] => Array
                (
                    [ID] => A11496
                    [CID] => 000020
                    [msgtype] => Periodic Report
                )

            [1] => Array
                (
                    [ID] => A11496
                    [CID] => 000020
                    [msgtype] => Periodic Report
                    
                )
        )       
    )   

Upvotes: 0

Views: 206

Answers (1)

Merijndk
Merijndk

Reputation: 1693

Try something likes this:

<?php
    $oldArray = array();
    $newArray = array();
    
    foreach($oldArray as $item){
        if(!isset($newArray[$item['ID']])){
            $newArray[$item['ID']] = [];
        }

        array_push($newArray[$item['ID']], $item);
    }
?>

Upvotes: 1

Related Questions