在一堆数据中按分数值由大到小取前N个数据,用小根堆的方法来实现,具体代码如下:
<?php
class TopN extends SplMinHeap
{
private $top_n;
/**
* @param int $top_n 前top_n名
*/
public function __construct($top_n)
{
$this->top_n = $top_n;
}
/**
* 添加一个元素
* @param number $score 排序值
* @param mixed $value 元素
*/
public function add($score,$value)
{
if ($this->top_n) {
$this->insert(array($score,$value));
$this->top_n--;
} else {
$top = $this->top();
if ($top[0] < $score) {
$this->extract();
$this->insert(array($score,$value));
}
}
}
/**
* 获取topN的结果
* @return array
*/
public function getResult()
{
$list = array();
while ($this->valid()) {
$value = $this->current();
$list[] = $value[1];
$this->next();
}
return array_reverse($list);
}
}
$mTopN = new TopN(3);
$mTopN->add(70,array(‘name‘=>‘张三‘,‘score‘=>70));
$mTopN->add(80,array(‘name‘=>‘李四‘,‘score‘=>80));
$mTopN->add(100,array(‘name‘=>‘王五‘,‘score‘=>100));
$mTopN->add(90,array(‘name‘=>‘赵六‘,‘score‘=>90));
$result = $mTopN->getResult();
print_r($result);
/*
Array
(
[0] => Array
(
[name] => 王五
[score] => 100
)
[1] => Array
(
[name] => 赵六
[score] => 90
)
[2] => Array
(
[name] => 李四
[score] => 80
)
)
*/