【问题标题】:order an array based on input - php [duplicate]根据输入订购数组 - php [重复]
【发布时间】:2017-01-21 11:16:54
【问题描述】:

PHP 中是否有任何方法可以拥有一个数组并按照与某个字符串最相似的方式对其进行排序。

例如:

$array = array("Bob", "Brad", "Britney");
$userinput = "Bradley123";

/*
function that changes the array to be
array("Brad","Britney","Bob")
from the most similar from the $userinput
*/

【问题讨论】:

  • 我认为没有办法做到这一点。
  • 你是如何定义“最相似”的?
  • 如果你指的是谷歌之类的东西,那么你应该使用数据库并通过它进行搜索,而不是使用数组。
  • 没有内置的方法可以做到这一点。您必须自己编写代码。您可能可以将链接到的 similar_text 函数 u_mulder 与 usort 结合使用。

标签: php arrays sorting


【解决方案1】:

我做了一些研究,这里有一个方法可以做到:

$array = array(0 => 'blue', 1 => 'reds', 2 => 'green', 3 => 'reds'); 
//Words to be searched from.

$res = array("percent" => "0", "word" => "N/A");
//Result, this is an array for the bellow loop to talk to.

foreach($array AS $ar){
  similar_text("red", $ar, $percent);

  //If it's more like the word, then replace the percentage with the percentage of similarity & word.
  if($percent > $res["percent"]){
    $res["percent"] = $percent;
    $res["word"] = $ar;
  }
}

//Echo out the most similar word.
echo $res["word"];

据我所知,这是做这种事情的唯一方法。

【讨论】:

  • 我已经尝试修改您的代码,以便它将所有结果都放在同一个数组中,但我一直失败。您是否知道将每个结果带入数组并以most 类似于least 类似的方式排序
  • 我实际上不知道这是否可能,我的意思是它会但不是每个循环都没有额外的。正如我所说,您可以使用数据库之类的东西,但是这个脚本已经完成了您刚才要求的操作,但没有将其放入数组中。
猜你喜欢
  • 1970-01-01
  • 2018-06-30
  • 2011-06-10
  • 1970-01-01
  • 2019-08-12
  • 1970-01-01
  • 2021-04-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多