排序带负片的浮点数组

时间:2013-01-22 03:28:44

标签: php arrays sorting floating-point negative-number

我不知道为什么会发生这种情况,也无法在Google上找到解决方案。

这是asort SORT_NUMERIC Array ( [0] => -5.092368092812E-9 [6] => -7.0826220389192E-13 [1] => 1.878703363826E-13 [2] => 1.8795587624424E-13 [3] => 2.3346288902754E-13 [4] => 3.0942295197372E-13 [5] => 7.9098357204299E-13 [7] => 1.1684494919952E-12 [8] => 1.1685043272518E-12 [9] => 1.1686030371986E-12 [11] => 8.0451267461732E-12 [12] => 3.7644522809587E-10 [13] => 3.7763249406879E-10 [14] => 3.7955309374295E-10 [15] => 8.7712602092571E-10 [16] => 2.8469968623087E-9 [17] => 2.8531226087777E-9 [10] => 6.2070895038159E-9 [18] => 1.0725026970778E-8 [20] => 1.4052528456163E-8 [21] => 1.4087656025218E-8 [19] => 2.0018554451113E-8 [22] => 1.130570524972E-7 [23] => 2.186127734393E-5 [25] => 0.0045965175663413 [24] => 0.51061752595249 ) 后的浮点数组:

{{1}}

如何正确分类?

非常感谢提前!

3 个答案:

答案 0 :(得分:2)

natsort将为您效劳。

<?php  
// do stuf
$array  = Array ( -5.092368092812E-9 , -7.0826220389192E-13 , 1.878703363826E-13
, 1.8795587624424E-13 , 2.3346288902754E-13 , 3.0942295197372E-13 ,
7.9098357204299E-13 , 1.1684494919952E-12 , 1.1685043272518E-12 ,
1.1686030371986E-12 , 8.0451267461732E-12 , 3.7644522809587E-10 ,
3.7763249406879E-10 , 3.7955309374295E-10 , 8.7712602092571E-10 ,
2.8469968623087E-9 , 2.8531226087777E-9 , 6.2070895038159E-9 ,
1.0725026970778E-8 , 1.4052528456163E-8 , 1.4087656025218E-8 ,
2.0018554451113E-8 , 1.130570524972E-7 , 2.186127734393E-5 ,
0.0045965175663413 , 0.51061752595249 );

$res = natsort($array);

echo "<pre>";
print_r($array);

?>

答案 1 :(得分:1)

这令人尴尬。

asort维护索引关联。 sort没有。使用sort

http://php.net/manual/en/array.sorting.php

答案 2 :(得分:0)

尝试此功能:

function masort(&$data, $sortby)
{
   static $sort_funcs = array();

   if (empty($sort_funcs[$sortby])) {
       $code = "\$c=0;";
       foreach (split(',', $sortby) as $key) {
         $array = array_pop($data);
         array_push($data, $array);
         if(is_numeric($array[$key]))
           $code .= "if ( \$c = ((\$a['$key'] == \$b['$key']) ? 0:((\$a['$key'] < \$b['$key']) ? -1 : 1 )) );";
         else
           $code .= "if ( (\$c = strcasecmp(\$a['$key'],\$b['$key'])) != 0 ) return \$c;\n";
       }
       $code .= 'return $c;';
       $sort_func = $sort_funcs[$sortby] = create_function('$a, $b', $code);
   } else {
       $sort_func = $sort_funcs[$sortby];
   }
   $sort_func = $sort_funcs[$sortby];
   uasort($data, $sort_func);
}

我拥有它,就像通用分拣机一样。