php usort

这个函数很倒霉,不容易控制

手册上确实是举例说明usort了,但是只是说,callback $cmp_function 返回值小于、等于、大于,表示第一个参数比第二个小、等、大。
可是在实践中,使用float比较、string直接比较,都会导致usort的行为不正常,就是无法正确的排序,
即使是使用float值比较,然后返回1,-1,0,都是不可以的,所以只能先把float转成int来比较
真是不知道如果我的float不是全部round 2的话,我怎么转化成int,只能自己写个冒泡了。。。






??? public static function tksort(&$arr, $strColumnName, $strOrder = 'ASC') {
??????? usort($arr, array(new TKSorter($strColumnName, $strOrder), "compare"));
??? }

/**
?* The class for sorting by some int columns.
?*
?*/
class TKSorter {
??? private $_cname;
??? private $_order = 'ASC';
??? // see http://80x86.cn/article.asp?id=1761
??? private $_multi = 100; // round is (, 2), so we just multiply 100 here
??? public function __construct($strColumnName, $strOrder = 'ASC', $intMulti = 100) {
??????? $this->_cname = $strColumnName;
??????? $this->_order = $strOrder;
??????? $this->_multi = $intMulti;
??? }
??? public function compare($a, $b) {
??????? if (is_numeric($a[$this->_cname]) && is_numeric($b[$this->_cname])) { // both are numbers
??????????? $dblM = (int)($a[$this->_cname] * $this->_multi) - (int)($b[$this->_cname] * $this->_multi);
??????????? if ($this->_order == 'ASC') {
??????????????? return $dblM;
??????????? } else {
??????????????? return 0 - $dblM;
??????????? }
??????? } else {
??????????? // 强行转化!
??????????? $va = (int)(((double)$a[$this->_cname]) * $this->_multi);
??????????? $vb = (int)(((double)$b[$this->_cname]) * $this->_multi);
??????????? $dblM = $va - $vb;
??????????? if ($this->_order == 'ASC') {
??????????????? return $dblM;
??????????? } else {
??????????????? return 0 - $dblM;
??????????? }
??????? }
??? }
}
?

你可能感兴趣的:(PHP,asp,vb)