数字排序具有混合类型值的数组

时间:2011-10-31 15:14:49

标签: php arrays sorting

我有一个像这样的混合数组:

$fruits = array(
    "lemon",
    "Lemon",
    20,
    "banana",
    "apple",
    "121",
    40,
    50
);

然后按如下方式应用sort()函数:

sort($fruits, SORT_NUMERIC);
foreach ($fruits as $key => $val) {
    echo "fruits[" . $key . "] = " . $val . "\n";
}

现在,我不理解输出:

fruits[0] = apple
fruits[1] = lemon
fruits[2] = banana
fruits[3] = Lemon
fruits[4] = 20
fruits[5] = 40
fruits[6] = 50
fruits[7] = 121

请解释为什么这样排序?

3 个答案:

答案 0 :(得分:3)

OP,因为sort();对大写和小写字符的效果不好,为什么不将所有内容转换为小写然后排序呢?

<?php
$fruits = array("lemon","Lemon", 20, "banana", "apple","121",40,50);
$fruits = array_map("strtolower", $fruits); //using strtolower

sort($fruits );
foreach ($fruits as $key => $val) {
    echo "fruits[" . $key . "] = " . $val . "\n";
}
?>

输出

fruits[0] = 20
fruits[1] = 40
fruits[2] = 50
fruits[3] = 121
fruits[4] = apple
fruits[5] = banana
fruits[6] = lemon
fruits[7] = lemon

答案 1 :(得分:2)

基本上它应该从A到Z然后按数字顺序排序,但是使用混合类型,函数不知道如何对数组进行排序并给出随机结果......

在手册页中有一个巨大的警告说:

  

排序具有混合类型值的数组时要小心,因为sort()   会产生不可预测的结果。

您可以在函数中添加参数:

  • SORT_REGULAR - 正常比较项目(不要更改类型)

  • SORT_NUMERIC - 以数字方式比较项目

  • SORT_STRING - 将项目比较为字符串

  • SORT_LOCALE_STRING - 根据当前区域设置将项目作为字符串进行比较。在PHP 4.4.0和5.0.2中添加,它使用系统区域设置,可以使用setlocale()进行更改。

根据php.net上的手册here

编辑1: 可能你可以使用标志SORT_REGULAR获得最佳排序结果,因为它不会改变变量类型,数字仍然是数字,字符串仍然是字符串,但它也会给你一个奇怪的结果

fruits[0] = 121
fruits[1] = Lemon
fruits[2] = apple
fruits[3] = banana
fruits[4] = lemon
fruits[5] = 20
fruits[6] = 40
fruits[7] = 50

我认为因为它比较了字符串中的ascii代码而La b l之前... 121首先是因为你把它写成字符串"121"

编辑2:

最好的方法是分离类型:(这样php会将“121”视为数字而不是字符串,但你可以简单地通过if子句来判断它)

<?php
$fruits = array("lemon","Lemon", 20, "banana", "apple","121",40,50);
$arr1=array();
$arr2=array();
      foreach($fruits as $key=>$val){
          if (is_numeric($val))
               array_push($arr1,$val); 
          else
              array_push($arr2,$val);
      }          
sort($arr1,SORT_NUMERIC);            
sort($arr2,SORT_LOCALE_STRING);
$fruits = array_merge($arr1,$arr2);
echo "<pre>";
foreach ($fruits as $key => $val) {
    echo "fruits[" . $key . "] = " . $val . "\n";
}
?>

答案 2 :(得分:1)

我相信sort($array, SORT_NUMERIC),无法转换为数字的值会被视为0并按此方式排序。由于示例中的所有字符串都变为0,因此 lemon 之前 lemon 是否真的无关紧要。这是一个例子:

<?php
$fruits = array("alpha", "bravo", -1, -0.001, 0, 0.001, 1, "x-ray", "zulu");
shuffle($fruits); // randomly re-arrange the items in array
sort($fruits, SORT_NUMERIC);
print_r($fruits);
// output -- pass 1
Array
(
    [0] => -1
    [1] => -0.001
    [2] => 0
    [3] => alpha
    [4] => x-ray
    [5] => zulu
    [6] => bravo
    [7] => 0.001
    [8] => 1
)
// output -- pass 2
Array
(
    [0] => -1
    [1] => -0.001
    [2] => bravo
    [3] => zulu
    [4] => 0
    [5] => x-ray
    [6] => alpha
    [7] => 0.001
    [8] => 1
)
// output -- pass 3
Array
(
    [0] => -1
    [1] => -0.001
    [2] => x-ray
    [3] => zulu
    [4] => 0
    [5] => bravo
    [6] => alpha
    [7] => 0.001
    [8] => 1
)
?>