views:

43

answers:

2

I have an array:

Array
(
    [customer] => One
    [itemno] => Yellow Ribbon
    [price] => 1,2

)
Array
(
    [customer] => One
    [itemno] => Blue Band
    [price] => 0,5
)
Array
(
    [customer] => Two
    [itemno] => Red Tape
    [price] => 2,0
)

And I want to group it by customer like this:

Array
(
    [One] => Array (
        [itemno] => Yellow Ribbon
        [price] => 1,2
        ) 
        [itemno] => Blue Band
        [price] => 0,5
        )

    [Two] => Array (
        [itemno] => Red Tape
        [price] => 2,0
        )
 )

How can I accomplish this?

A: 
$newArray =array(); 
foreach($originalArray as $item){
  if(!array_key_exists($item->customer, $newArray)){
      $newArray[$item->customer]= array();
  }
  $newArray[$item->customer][] = $item;
}

//the end result will be $newArray = array('customer1'=>array( customers...), 'customer2'=>array(customers...));

Chris
+2  A: 

If we will call the first array $start and the last $finish, then:

$finish = array();
foreach ($start as $v){
  $finish[$v['customer']][] = array('itemno'=>$v['itemno'], 'price'=>$v['price']);
}
AndreyKo
Will this produce a warning when strict reporting is enabled?
Chris