我有一个包含项目的数组,每个项目都有一个duration
和一个price
。
我想根据duration
值过滤掉重复的price
值 - 保持最低值。
阵列:
$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 :(得分: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,
),
)
答案 1 :(得分:0)
怎么样?
$collection = collect($arr);
$filtered = $collection->sortBy('duration')->sortBy('price')->unique('duration');
它也可以作为
$collection = collect($arr);
$filtered = $collection->sortBy('price')->unique('duration');