php数据库根据相似度排序,php数组字段相似度排序

摘要:今天有一个客户有这么一个需求,要求对某篇文章的相关内容的列表,在跟文章标题进行相似度排序,于是想了又想,写了一个小算法,可以根据关键字相似度对数组某个字段进行排序...

今天有一个客户有这么一个需求,要求对某篇文章的相关内容的列表,在跟文章标题进行相似度排序,于是想了又想,写了一个小算法,可以根据关键字相似度对数组某个字段进行排序。

废话少说,直接上代码://原数据

$data = [

[

'id'=>1,

'title'=>'YzmCMS内容管理系统',

],

[

'id'=>2,

'title'=>'开源CMS',

],

[

'id'=>3,

'title'=>'YzmCMS轻量级开源内容管理系统',

],

[

'id'=>4,

'title'=>'内容管理系统',

],

[

'id'=>5,

'title'=>'免费内容管理系统',

],

[

'id'=>6,

'title'=>'YzmCMS开源CMS',

],

[

'id'=>7,

'title'=>'免费CMS',

],

[

'id'=>8,

'title'=>'轻量级开源CMS',

],

[

'id'=>9,

'title'=>'YzmCMS建站CMS',

],

[

'id'=>10,

'title'=>'免费开源CMS',

],

];

处理方法:/**

* 根据关键字对数组字段进行相似度排序

* @param   $array   原数组

* @param   $keyword 关键字

* @param   $arr_key 要匹配的数组字段名

* @return  array    排序好的数组

*/

function similar_arr($array, $keyword, $arr_key = 'title'){

//数组key小于3,直接返回,不符合排序要求(特例,可不写)

if(count($array)<= 3){

return $array;

}

//数组相似度处理

foreach ($array as $key => $value) {

similar_text($value[$arr_key], $keyword, $percent);

$value['percent'] = $percent;

$data[] = $value;

}

//取出数组中percent的一列,返回一维数组

$percent =  array_column($data, 'percent');

//排序,根据 percent 排序

array_multisort($percent, SORT_DESC, $data);

return $data;

}

使用方法:$res = similar_arr($data, 'YzmCMS');

var_dump($res);

运行结果:array(10) {

[0]=>

array(3) {

["id"]=>

int(6)

["title"]=>

string(15) "YzmCMS开源CMS"

["percent"]=>

float(57.142857142857)

}

[1]=>

array(3) {

["id"]=>

int(9)

["title"]=>

string(15) "YzmCMS建站CMS"

["percent"]=>

float(57.142857142857)

}

[2]=>

array(3) {

["id"]=>

int(1)

["title"]=>

string(24) "YzmCMS内容管理系统"

["percent"]=>

float(40)

}

[3]=>

array(3) {

["id"]=>

int(2)

["title"]=>

string(9) "开源CMS"

["percent"]=>

float(40)

}

[4]=>

array(3) {

["id"]=>

int(7)

["title"]=>

string(9) "免费CMS"

["percent"]=>

float(40)

}

[5]=>

array(3) {

["id"]=>

int(10)

["title"]=>

string(15) "免费开源CMS"

["percent"]=>

float(28.571428571429)

}

[6]=>

array(3) {

["id"]=>

int(3)

["title"]=>

string(39) "YzmCMS轻量级开源内容管理系统"

["percent"]=>

float(26.666666666667)

}

[7]=>

array(3) {

["id"]=>

int(8)

["title"]=>

string(18) "轻量级开源CMS"

["percent"]=>

float(25)

}

[8]=>

array(3) {

["id"]=>

int(4)

["title"]=>

string(18) "内容管理系统"

["percent"]=>

float(0)

}

[9]=>

array(3) {

["id"]=>

int(5)

["title"]=>

string(24) "免费内容管理系统"

["percent"]=>

float(0)

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值