素材牛VIP会员
PHP数组字段相似度排序
 素材牛小二  分类:PHP代码  人气:1303  回帖:0  发布于4年前 收藏

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

废话少说,直接上代码:

//原数据
$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)垃圾回帖将一律封号处理……

暂无回帖!
 文明上网,理性发言!   😉 阿里云幸运券,戳我领取