数字排序混合类型值的数组 [英] Numeric sort an array with mixed types values
问题描述
我有一个混合阵列是这样的:
I have a mixed array like this:
$fruits = array(
"lemon",
"Lemon",
20,
"banana",
"apple",
"121",
40,
50
);
再申请排序()
如下功能吧:
sort($fruits, SORT_NUMERIC);
foreach ($fruits as $key => $val) {
echo "fruits[" . $key . "] = " . $val . "\n";
}
现在,我不明白的输出是:
Now, i do not understand the output that is:
fruits[0] = apple
fruits[1] = lemon
fruits[2] = banana
fruits[3] = Lemon
fruits[4] = 20
fruits[5] = 40
fruits[6] = 50
fruits[7] = 121
请解释为什么它的排序呀?
Please explain why it is sorted that way?
推荐答案
基本上它应该从一种到Z然后通过数字顺序,但使用混合型功能不知道如何对数组进行排序,并给予一个随机的结果。 ..
basically it should sort from A to Z then by numeric order, but using mixed type the function do not know how to sort the array and give a random result...
在手册中有一个巨大的警告说:
in the manual page there is a huge warning says that:
排序混合类型的值数组时要小心,因为排序()
可生产未predictable结果。
Be careful when sorting arrays with mixed types values because sort() can produce unpredictable results.
您可以将参数添加到功能:
you can add a parameter to the function:
-
SORT_REGULAR - 比较项目正常(不改变类型)
SORT_REGULAR - compare items normally (don't change types)
SORT_NUMERIC - 数值比较
SORT_NUMERIC - compare items numerically
SORT_STRING - 对象进行字符串比较
SORT_STRING - compare items as strings
SORT_LOCALE_STRING - 对象进行字符串比较,基于当前区域。加入PHP 4.4.0和5.0.2,它使用的系统区域设置,可以使用的setlocale()来改变。
SORT_LOCALE_STRING - compare items as strings, based on the current locale. Added in PHP 4.4.0 and 5.0.2, it uses the system locale, which can be changed using setlocale().
According to manual here on php.net
编辑1:
也许你能获得使用标志的最好排序的结果 SORT_REGULAR
,因为它不会改变变量的类型和数量仍然是数字和字符串保持字符串但它也会给你一个奇怪的结果
Edit 1:
Probably you can obtain the best sort result using the flag SORT_REGULAR
because it does not change the variable type and numbers remain numbers and strings remain strings but it will also give you a strange result
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 code和→
为前 ABL
...
121排在首位,因为你写它像一个字符串121
编辑2:
进行最好的办法是分开类型:这样的PHP将把121为数字,而不是一个字符串(,但你完全可以通过如果$ C决定吧$ C>子句)
The best way to proceed is to separate the types: (this way php will treat "121" as a number and not a string, but you can simply decide it by the if
clause)
<?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";
}
?>
这篇关于数字排序混合类型值的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!