简体   繁体   中英

Need help splitting an array

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

My array:

array(size=5)
  0=>
    array(size=3)
      'oid' => int 1
      payment_status => 'Paid'
      payment_type => 'Online'
  1=>
    array(size=3)
      'oid' => int 1
      payment_status => 'Paid'
      payment_type => 'Online'
  2=>
    array(size=3)
      'oid' => int 1
      payment_status => 'Paid'
      payment_type => 'Online'
  3=>
    array(size=3)
      'oid' => int 2
      payment_status => 'Paid'
      payment_type => 'Online'
  4=>
    array(size=3)
      'oid' => int 2
      payment_status => 'Paid'
      payment_type => 'Online'

I am trying to split this array like this:

array(size=3)
  0=>
    array(size=3)
      'oid' => int 1
      payment_status => 'Paid'
      payment_type => 'Online'
  1=>
    array(size=3)
      'oid' => int 1
      payment_status => 'Paid'
      payment_type => 'Online'
  2=>
    array(size=3)
      'oid' => int 1
      payment_status => 'Paid'
      payment_type => 'Online'

and

array(size=2)
  0=>
    array(size=3)
      'oid' => int 2
      payment_status => 'Paid'
      payment_type => 'Online'
  1=>
    array(size=3)
      'oid' => int 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? Thanks

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM