如何通过更多键对多维数组进行分组

时间:2017-10-26 20:41:03

标签: php arrays multidimensional-array grouping

这是我的阵列来源。

//array for all reception
    $reception = array(
        array('code'=>'AB202','order'=>'111111','qty'=>'50.000'),
        array('code'=>'AB202','order'=>'111111','qty'=>'50.000'),
        array('code'=>'AB202','order'=>'222222','qty'=>'50.000'),
        array('code'=>'AB300','order'=>'666666','qty'=>'100.000'),
        array('code'=>'AB300','order'=>'666666','qty'=>'120.000'),
        array('code'=>'AB300','order'=>'777777','qty'=>'120.000')          
        );

代码AB202等于订单111111 AND 222222

订单111111等于qty => 50,qty => 50
订单222222等于qty => 50

代码AB300等于订单666666和777777

订单666666等于qty => 100,qty => 120

订单777777等于qty => 120

我希望按照代码和顺序分组

Array
(
  [AB202] => Array    //array code
    (
      [111111] => Array     //array order
          (         
              [0] => 50.000    // qty
              [1] => 50.000
          )
      [222222] => Array
          (         
              [0] => 50.000
          ) 
    )

    [AB300] => Array
    (
      [666666] => Array
          (         
              [0] => 100.000
              [1] => 120.000
          )
      [777777] => Array
          (         
              [0] => 120.000
          ) 
    )


)

1 个答案:

答案 0 :(得分:0)

循环遍历所有接收,然后检查代码密钥或订单密钥是否存在,如果不存在则创建一个,然后附加每个数量

$newArr = array();
foreach ($reception as $code) {
    if (!array_key_exists($code['code'], $newArr)){
        $newArr[$code['code']] = array();
    }
    if (!array_key_exists($code['order'], $newArr[$code['code']])) {
        $newArr[$code['code']][$code['order']] = array();
    }
    array_push($newArr[$code['code']][$code['order']], $code['qty']);
}