2017-07-23 56 views
0

我需要按日期分組我的多維數組。如何通過子數組值對多維數組進行分組?

例如:

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

所需輸出陣列結構似乎有點怪,但這將做到這一點:

代碼:(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', 
), 
)