按列对二维数组进行分组,并将整行推入每个组[重复]

问题描述 投票:0回答:2

我有一个数组:

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
)

我想按客户对其进行分组,如下所示:

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

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

我怎样才能做到这一点?

php arrays multidimensional-array grouping sub-array
2个回答
3
投票

如果我们调用第一个数组 $start 和最后一个数组 $finish,那么:

$完成=数组();
foreach ($start as $v){
  $finish[$v['客户']][] = array('itemno'=>$v['itemno'], 'price'=>$v['price']);
}

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

//最终结果将是 $newArray = array('customer1'=>array(customers...), 'customer2'=>array(customers...));

© www.soinside.com 2019 - 2024. All rights reserved.