按匹配数量排序数组,并将最适合的第一个PHP

时间:2018-05-18 23:46:46

标签: php sorting best-fit

我创建了基于标签的搜索,并希望根据相关性对搜索结果进行排序。最佳拟合和标签数量是相关的。想象一下这是搜索查询:

$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
  ]
];

1 个答案:

答案 0 :(得分: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>';

http://phpio.net/s/7yhb