如何按子阵列值对多维数组数据进行分组?

时间:2017-07-23 11:53:22

标签: php multidimensional-array grouping associative-array

我需要按日期对多维数组进行分组。

例如:

Array
(    
    [0] => Array
        (
            [product_id] => 52
            [date] => 2017-07-28
        )
    [1] => Array
        (
            [product_id] => 53
            [date] => 2017-07-30
        )
    [2] => Array
        (
            [product_id] => 123
            [date] => 2017-07-30
        )
)

我需要这个结果:

Array
(
     [2017-07-30] => Array
        (
            [0] => Array
                (
                    [product_id] => 123
                    [date] => 2017-07-30
                )
            [1] => Array
                (
                    [product_id] => 53
                    [date] => 2017-07-30
                )
        )    
    [2017-07-28] => Array
        (
            [product_id] => 52
            [date] => 2017-07-28
        )
)

这是我的编码尝试:

foreach($products as $product){
    $array = array($product['date']=>array('pid'=>$product['product_id'])‌​); 
    if(!empty($deliverdates)){ 
        if(in_array($product['date'],array_keys($_SESSION["carts‌​all"]))){ 
            foreach($deliverdates as $k => $v){
                if($product['date'] == $k){
                    array_push($deliverdates[$k], $array);
                }
            }
        }else{
            $deliverdates = array_merge($deliverdates,$array);
        }
    }else{
        $deliverdates = $array;
    }
}

1 个答案:

答案 0 :(得分:0)

你想要的输出数组结构看起来有点奇怪,但是这样做了:

代码:(Demo

$array=[
    ['product_id'=>52,'date'=>'2017-07-28'],
    ['product_id'=>53,'date'=>'2017-07-30'],
    ['product_id'=>123,'date'=>'2017-07-30']
];
rsort($array);  // it appears that you want DESC order
foreach($array as $a){
    if(!isset($result[$a['date']])){
        $result[$a['date']]=$a;  // no index on first instance
    }elseif(isset($result[$a['date']]['product_id'])){
        $result[$a['date']]=[$result[$a['date']],$a];  // on second instance of date, change structure
    }else{
        $result[$a['date']][]=$a;  // index new additions normally
    }
}
var_export($result);

输出:

array (
  '2017-07-30' => 
  array (
    0 => 
    array (
      'product_id' => 123,
      'date' => '2017-07-30',
    ),
    1 => 
    array (
      'product_id' => 53,
      'date' => '2017-07-30',
    ),
  ),
  '2017-07-28' => 
  array (
    'product_id' => 52,
    'date' => '2017-07-28',
  ),
)