2014-03-02 152 views
-1

我有2個數組。PHP按鍵合併數組

貨物陣列和分離器陣列。

$goods = [ 
    [ 
     'good_id' => '1', 
     'name' => 'Good 1', 
    ], 
    [ 
     'good_id' => '24', 
     'name' => 'Good 24', 
    ], 
    [ 
     'good_id' => '335', 
     'name' => 'Good 335', 
    ], 
    [ 
     'good_id' => '1986', 
     'name' => 'Good 1986', 
    ], 
]; 

$separators = [ 
    [ 
     'id' => '1', 
     'good_id' => '0', 
     'name' => 'Separator 1', 
    ], 
    [ 
     'id' => '2', 
     'good_id' => '0', 
     'name' => 'Separator 2', 
    ], 
    [ 
     'id' => '3', 
     'good_id' => '4', 
     'name' => 'This separator should set after 4 good_id and before 5 good_id if exists', 
    ], 
    [ 
     'id' => '4', 
     'good_id' => '47', 
     'name' => 'This separator should set after 47 good_id and before 48 good_id if exists', 
    ], 
    [ 
     'id' => '5', 
     'good_id' => '9999', 
     'name' => 'This separator should set after 9999 good_id and before 10000 good_id if exists', 
    ], 
    [ 
     'id' => '6', 
     'good_id' => '9999', 
     'name' => 'This separator should set after 9999 good_id and AFTER prevously separator AND before 10000 good_id if exists', 
    ] 

]; 

我需要通過good_id合併這個數組。 Spearators good_id應該設置good_id之後的商品good_id。

$merged = [ 
    [ 
     'id' => '1', 
     'good_id' => '0', 
     'name' => 'Separator 1', 
    ], 
    [ 
     'id' => '2', 
     'good_id' => '0', 
     'name' => 'Separator 2', 
    ], 
    [ 
     'good_id' => '1', 
     'name' => 'Good 1', 
    ], 
    [ 
     'id' => '3', 
     'good_id' => '4', 
     'name' => 'This separator should set after 4 good_id and before 5 good_id if exists', 
    ], 
    [ 
     'good_id' => '24', 
     'name' => 'Good 24', 
    ], 
    [ 
     'id' => '4', 
     'good_id' => '47', 
     'name' => 'This separator should set after 47 good_id and before 48 good_id if exists', 
    ], 
    [ 
     'good_id' => '335', 
     'name' => 'Good 335', 
    ], 
    [ 
     'good_id' => '1986', 
     'name' => 'Good 1986', 
    ], 
    [ 
     'id' => '5', 
     'good_id' => '9999', 
     'name' => 'This separator should set after 9999 good_id and before 10000 good_id if exists', 
    ], 
    [ 
     'id' => '6', 
     'good_id' => '9999', 
     'name' => 'This separator should set after 9999 good_id and AFTER prevously separator AND before 10000 good_id if exists', 
    ] 

]; 

回答

0

據我所知,您需要合併兩個數組,並按good_id子鍵排序結果。假設這些陣列沒有相同記錄good_id鍵,您可以使用以下簡單解決方案:

$merged = array_merge($goods, $separators); 
usort($merged, function ($a, $b) { 
    return $a['good_id'] < $b['good_id']? -1 : 1; 
}); 
+0

usort不返回數組。 –