如何通过匹配最接近输入字符串来排序数组?

时间:2016-12-20 10:52:30

标签: php arrays sorting

我希望通过使数组中最接近的值匹配来对数组进行排序。

到目前为止我所拥有的:

$array = array("Year 6", "Year 4", "Eden camp trip", "Easter school", "Eden camp trip", "Year 6 Chester Zoo", "Year 6 Trip to Chester");

$search = strtolower("Year 6");

usort($array, function ($a, $b) use ($search) {
    similar_text($search, $a, $aa);
    similar_text($search, $b, $bb);
    return $aa === $bb ? 0 : ($aa > $bb ? -1 : 1);
});

echo "<pre>";
     print_r($array);
echo "</pre>";

结果:

Array
(
    [0] => Year 6
    [1] => Year 4
    [2] => Year 6 Chester Zoo
    [3] => Year 6 Trip to Chester
    [4] => Easter school
    [5] => Eden camp trip
    [6] => Eden camp trip
)

预期结果:

Array
(
    [0] => Year 6
    [1] => Year 6 Chester Zoo
    [2] => Year 6 Trip to Chester
    [3] => Year 4 
    [4] => Easter school
    [5] => Eden camp trip
    [6] => Eden camp trip
)

1 个答案:

答案 0 :(得分:0)

好的接受@AlexBlex建议..我去研究并找到了以下做我正在寻找的方式。

$array = array("Year 6", "Year 4", "Eden camp trip", "Easter school", "Eden camp trip", "Year 6 Chester Zoo", "Year 6 Trip to Chester");

$search = strtolower("Year 6");

usort($array, function($a, $b) use ($search) {

        $a = strtolower($a);
        $b = strtolower($b);

        if ($a == $search) return -1;
        if ($b == $search) return 1;

        $x = strpos($a, $search);
        $y = strpos($b, $search);

        if ($x !== false && $y === false) return -1;
        if ($y !== false && $x === false) return 1;
        if ($x !== false && $y !== false) { 

            if ($x != $y)  return $x > $y ? 1 : -1;

            $al = strlen($a);
            $bl = strlen($b);

            if ($al != $bl)  return $al > $bl ? 1 : -1;

            return 0;
        }

        $ac = levenshtein($search, $a);
        $bc = levenshtein($search, $b);

        if ($ac != $bc) return $ac > $bc ? 1 : -1;

        return 0;
 });

    echo "<pre>";
         print_r($array);
    echo "</pre>";

结果:

Array
(
    [0] => Year 6
    [1] => Year 6 Chester Zoo
    [2] => Year 6 Trip to Chester
    [3] => Year 4
    [4] => Easter school
    [5] => Eden camp trip
    [6] => Eden camp trip
)