2017-06-01 49 views
0

我有一個包含項目的數組,每個項目有一個durationprice基於同一陣列中其他條目的濾波器陣列

我想根據price值過濾掉重複的duration值 - 保持最低值。

陣:

$arr = [ 
    [ 
    'duration' => 60, // this item should be filtered 
    'price' => 100 
    ], 
    [ 
    'duration' => 120, 
    'price' => 190 
    ], 
    [ 
    'duration' => 60, // this one should remain in array 
    'price' => 75 
    ] 
] 

我使用Laravel作爲一個框架,所以我能夠使用收集的方法。

所以我現在做到這一點,如下所示:

$arr->sortByDesc('price') 
    ->keyBy('duration') // duplicate entries are overwritten 
         // with the latest/lowest value 
    ->sortBy('price'); 

但是,這感覺有點粗略...

回答

0

什麼布特

$collection = collect($arr); 
$filtered = $collection->sortBy('duration')->sortBy('price')->unique('duration'); 

它應該也可以作爲

$collection = collect($arr); 
$filtered = $collection->sortBy('price')->unique('duration'); 
+0

我不使用Laravel,但基於我在手冊中閱讀,Simone的第二種方法似乎是最好的'collection'方法。它排序ASC和唯一()保持第一次出現。 – mickmackusa

1

這將這樣的伎倆:

$arr = [ 
    [ 
    'duration' => 60, // this item should be filtered 
    'price' => 100 
    ], 
    [ 
    'duration' => 120, 
    'price' => 190 
    ], 
    [ 
    'duration' => 60, // this one should remain in array 
    'price' => 75 
    ] 
]; 

rsort($arr); // sort the subarrays by duration DESC 
// assign keys to each subarray using duration value 
$arr=array_values(array_combine(array_column($arr,'duration'),$arr)); 
// this overwrites more expensive subarrays with less expensive subarrays 
var_export($arr); 

輸出:

array (
    0 => 
    array (
    'duration' => 120, 
    'price' => 190, 
), 
    1 => 
    array (
    'duration' => 60, 
    'price' => 75, 
), 
)