php - 按匹配数量对数组进行排序,并将最适合的放在第一位 php
问题描述
我创建了一个基于标签的搜索,并希望根据相关性对搜索结果进行排序。最佳拟合和标签数量相关。想象一下这是搜索查询:
$search = ['A', 'B'];
这是结果:
$result = [
[
'id' => 3011,
'tags' => ['A', 'B', 'C']
],
[
'id' => 10798,
'tags' => ['A','C','D','E']
],
[
'id' => 92,
'tags' => ['A']
],
[
'id' => 4237,
'tags' => ['A', 'B']
]
];
我想重组整个事情如下:
$sortResult = [
[
'id' => 4237,
'tags' => ['A', 'B'] // At first place because has 2 values and the search 2, difference 0 and matched good to search
],
[
'id' => 3011,
'tags' => ['A', 'B', 'C'] // At second place because has 3 values and the search 2, difference 1 and matched good to search
],
[
'id' => 92,
'tags' => ['A'] // At third place because has 1 value and the search 2, difference 1
],
[
'id' => 10798,
'tags' => ['A','C','D','E'] // Down here because has 4 values and the search 2, difference 2
]
];
解决方案
不确定这是否适用于所有情况,但它为您的当前数据提供了所需的结果:
<?php
$search = ['A', 'B'];
$result = [
[
'id' => 3011,
'tags' => ['A', 'B', 'C'],
],
[
'id' => 10798,
'tags' => ['A', 'C', 'D', 'E'],
],
[
'id' => 92,
'tags' => ['A'],
],
[
'id' => 4237,
'tags' => ['A', 'B'],
],
];
usort($result, function ($a, $b) use ($search) {
$simA = count(array_intersect($a['tags'], $search));
$simB = count(array_intersect($b['tags'], $search));
$diffA = count(array_diff($a['tags'], $search));
$diffB = count(array_diff($b['tags'], $search));
$absA = abs(count($a['tags']) - count($search));
$absB = abs(count($b['tags']) - count($search));
$score = 0;
$score += $simB - $simA;
$score += $diffA - $diffB;
$score += $absA - $absB;
return $score;
});
echo '<pre>';
print_r($result);
echo '</pre>';
推荐阅读
- excel - 宏在我的 PC 上的运行与在另一台 PC 上的运行不同
- selenium - 无法使用 cypress 找到“iframe”
- netlogo - 什么代码可以使乌龟和补丁变量的下限保持在零以上?
- r - R CMD 检查注意:`No visible binding for global variable`,当在 S3 泛型中定义变量并在方法中使用它时
- javascript - 从模块导入异步函数
- r - R中的百分位数类别
- docker - 我的 Docker 无法在我的 Windows 10 Pro 上启动
- r - R:如果值不在另一个列表中,则过滤数据框行
- c# - 通用类 EF Core
- r - 使用 R-devel 进行 R CMD 检查:注意 Rd 文件中 \href{} 内的“https://doi.org/...”地址