Skip to content
Advertisement

Group array rows by column value and create subarrays in each group

I have an array like the following:

Array
(
[0] => Array
    (
        [record_id] => 3
        [task_date] => 2018-10-02
    )

[1] => Array
    (
        [record_id] => 5
        [task_date] => 2018-10-02
    )

[2] => Array
    (
        [record_id] => 1
        [task_date] => 2018-09-27
    )

)

I would like it to be in the following format:

Array
    (
        [0] => Array
            (
            [0] => Array
            (
                [record_id] => 3
                [task_date] => 2018-10-02
            )
            [1] => Array
            (
                [record_id] => 5
                [task_date] => 2018-10-02
            )
            )
        [1] => Array
         (
               [0] => Array
            (
                [record_id] => 1
                [task_date] => 2018-09-27
            )
         )
    )

so that each sub-array contains elements of the same date.

Advertisement

Answer

You can do this way.

$inputArray = array("0"=>array('record_id'=>'3','task_date'=>'28-10-02'),'1'=>array('record_id'=>'3','task_date'=>'28-10-02'),'2'=>array('record_id'=>'3','task_date'=>'28-10-03'));

$outputArray    =   array();
foreach($inputArray as $key=>$value){
    $outputArray[$value['task_date']][]=$value;
}

print_r(array_values($outputArray));
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement