Php 基于同一数组中的其他项筛选数组
我有一个包含项目的数组,每个项目都有一个Php 基于同一数组中的其他项筛选数组,php,arrays,laravel,sorting,duplicates,Php,Arrays,Laravel,Sorting,Duplicates,我有一个包含项目的数组,每个项目都有一个持续时间和一个价格 我想根据价格值筛选出重复的持续时间值-保持最低 数组: $arr = [ [ 'duration' => 60, // this item should be filtered 'price' => 100 ], [ 'duration' => 120, 'price' => 190 ], [ 'duration' => 60, // this o
持续时间
和一个价格
我想根据价格
值筛选出重复的持续时间
值-保持最低
数组:
$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');
但这感觉有点简略…这就可以了:
$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,
),
)
那怎么办
$collection = collect($arr);
$filtered = $collection->sortBy('duration')->sortBy('price')->unique('duration');
它也应该起到同样的作用
$collection = collect($arr);
$filtered = $collection->sortBy('price')->unique('duration');
我不使用Laravel,但根据我在手册中读到的内容,Simone的第二种方法似乎是最好的
collection
方法。它对ASC进行排序,unique()保留第一次出现的内容。