布隆过滤器的原理可以参考这里,非常详细:http://imhuchao.com/1271.html
以下程序是为了理解其原理,仅供参考。其中,哈希函数的数量,位数组的大小都有计算公式,可以参考上文链接。本程序为了简单起见,直接写死。
class Bloom {
// 哈希函数的数量
protected $hashNum = 10;
// 位数组的大小
protected $bitArrayCount = 6000;
// 位数组
protected $bitArray = [];
public function __construct()
{
// 构建默认的位数组,全部置为 false
$this->bitArray = array_pad([], $this->bitArrayCount, false);
}
/**
* 获取 hash 函数;也就是在位数组中,需要改为 true 的索引
* @param string $item 元素
* @return array
*/
protected function getIndexes($item): array
{