有没有PHP函数可以解决另一个数组值字符串中的数组值匹配问题?

时间:2019-04-16 21:45:49

标签: php arrays sorting search

我正在创建单词搜索,但我想根据搜索关键字的最高存在对其进行排名。我怎么解决这个问题?

我正在尝试搜索数组2长字符串中是否存在数组1键,然后按数组2在数组1中的总出现次数对数组进行排序。

打击是我的代码

$str = "Hello World January Jude";
$arr1 = ["Hello World January Jude Lol Love","Hello Lol Loop","Love Life Jude","Crude Flash Hello"];
$str = explode(" ", $str);
echo sort_base($arr1, $str);
function sort_base($arr, $str){
$count = "";
foreach ($arr as $valuer){
    foreach ($str as $value){
    //$list[] = strpos($valuer, $value, 0);
    $count .= strpos($valuer, $value, 0)."<hr/>"; 
}

}
$arr = trim($count," ");
 echo $arr;
}

示例输入:

$array = ["Say Hello","Hello World"," Hello World Cup Final","Hello Cup","Hello","World"]; 
$str = "Hello World Cup"; 

期望输出

按顺序排列:

  1. 你好世界杯
  2. 最终的Hello World
  3. 你好杯
  4. 你好
  5. 世界
  6. 问好

2 个答案:

答案 0 :(得分:1)

You can use array-intersect and count to achieve number value of the similar words. Now you can use usort for sort by that.

Consider the following:

function sort_most_exists_asc($arr, $str) {
    usort($arr, function ($a, $b) use ($str) {
        $aa = count(array_intersect(explode(" ", $str), explode(" ", $a)));
        $bb = count(array_intersect(explode(" ", $str), explode(" ", $b)));
        return $bb - $aa;
    });
    return $arr;
}

$str = "Hello World January Jude";
$arr = ["Hello World January Jude Lol Love","Hello Lol Loop","Love Life Jude","Crude Flash Hello"];
$arr = sort_most_exists_asc($arr, $str);

Live example: 3v4l

Notice this will work only for whole words. For words similarity use Levenshtein distance - and compare by that in the usort

答案 1 :(得分:0)

You can create a set of all the matching words between each phrase and the target list of words.

foreach ($arr1 as $phrase) {
    $matches[] = array_intersect(str_word_count($phrase, 1), $str);
}

That array of matches can be used with array_multisort to reorder the original array.

array_multisort($matches, SORT_DESC, $arr1);