gpt4 book ai didi

php - 按范围 10 x 10 对数组进行排序

转载 作者:行者123 更新时间:2023-12-03 08:04:48 25 4
gpt4 key购买 nike

你认为我可以优化这段 PHP 代码吗?此代码按范围对数组进行排序,因为脚本将在 30000 次迭代的循环中打开。

Array
(
[0] => 39.89
[1] => 49.62
[2] => 59
[3] => 70.9
[4] => 82
[5] => 109.2
[6] => 120
[7] => 138
)

循环

    $newArr = [];
foreach ($formField['surface_m2'] as $key => $surface) {
if (substr($surface, -1) < 5){
$value = floor($surface / 10) *10;
} else{
$value = ceil($surface / 10) *10;
$value -= 10;
}

if(!empty($newArr[$value])){
$newArr[$value][] = $surface;
}else{
$newArr[$value] = [];
$newArr[$value][] = $surface;
}
}

退出

Array(
[30] => Array( [0] => 39.89 )
[40] => Array( [0] => 49.62 )
[50] => Array( [0] => 59 )
[70] => Array( [0] => 70.9 )
[80] => Array( [0] => 82 )
[100] => Array( [0] => 109.2 )
[120] => Array( [0] => 120 )
[130] => Array( [0] => 138 )
)

最佳答案

像这样:

foreach ($formField['surface_m2'] as $number) {
$newArr[$number - $number % 10][] = $number;
}

从数字中减去 $number % 10 将导致数字被截断到十位。

ksort($newArr); 如果您需要对组进行排序,则按键对组进行排序。

并对组进行排序:

foreach ($newArr as &$group) {
sort($group);
}

不过,在对整个数组进行分组之前对其进行sort() 可能会更有效。我不确定。


实际上,我很好奇,所以我做了一些测试,对于较小的数组(计数 < 300),在分组之前进行排序似乎更快,但对于较大的数组则更慢。不过差别不大 (≈10%)。

关于php - 按范围 10 x 10 对数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54712617/

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