Search code examples
phparraysmultidimensional-arraygrouping

Group 2d array rows by column value


I am trying to split an array into 2 or more arrays. Here is what I am trying to do:

My array:

[
    ['oid' => 1, 'payment_status' => 'Paid', 'payment_type' => 'Online'],
    ['oid' => 1, 'payment_status' => 'Paid', 'payment_type' => 'Online'],
    ['oid' => 1, 'payment_status' => 'Paid', 'payment_type' => 'Online'],
    ['oid' => 2, 'payment_status' => 'Paid', 'payment_type' => 'Online'],
    ['oid' => 2, 'payment_status' => 'Paid', 'payment_type' => 'Online']
]

I am trying to split this array like this:

[
    ['oid' => 1, 'payment_status' => 'Paid', 'payment_type' => 'Online'],
    ['oid' => 1, 'payment_status' => 'Paid', 'payment_type' => 'Online'],
    ['oid' => 1, 'payment_status' => 'Paid', 'payment_type' => 'Online']
]

and

[
    ['oid' => 2, 'payment_status' => 'Paid', 'payment_type' => 'Online'],
    ['oid' => 2, 'payment_status' => 'Paid', 'payment_type' => 'Online']
]

So as you can see the array gets split into multiple arrays based on 'oid' value. Can anyone tell me how to achieve this output?


Solution

  • simple one, copy the items based on oid into a new array:

    $input = $yourArray;
    
    $output = array();
    
    foreach($input as $item)
    {
        $output[$item['oid']][] = $item;
    }
    
    var_dump($output);
    

    output holds an array with oid as key.

    you can access your separated array like this:

    $output[1]; //for oid 1
    $output[2]; //for oid 2
    

    and so on