gpt4 book ai didi

php - 数字对具有混合类型值的数组进行排序

转载 作者:可可西里 更新时间:2023-11-01 00:35:51 27 4
gpt4 key购买 nike

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

$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

请解释为什么这样排序?

最佳答案

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

关于php - 数字对具有混合类型值的数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7955651/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com