Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort array by range 10 by 10

Do you think i can optimize this piece of PHP code? This code sorting a array by range because the script will turn on in a loop of 30000 iteration.

IN

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

LOOP

    $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;
        }
    }

OUT

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 )
)
like image 931
Sco Avatar asked Apr 22 '26 02:04

Sco


2 Answers

Like this:

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

Subtracting $number % 10 from the number will result in the number truncated to the tens place.

ksort($newArr); to sort the groups by keys if you need it to be sorted.

And to sort the groups:

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

It may be more efficient to just sort() the entire array before grouping it, though. I'm not sure.


Actually, I was curious so I did some testing, and sorting before grouping seems to be faster for smaller arrays (count < 300), but slower for larger arrays. It's not a big difference, though (≈10%).

like image 173
Don't Panic Avatar answered Apr 23 '26 14:04

Don't Panic


$newArr = [];
foreach($in as $surface) {
    $key = (int) ($surface/10)*10;
    $newArr[$key] []= $surface;
}

By casting to int the value is rounded down. It is then added to the corresponding post in $newArr. Done this way PHP "assumes" it should start out with an empty array.

like image 31
Torbjörn Stabo Avatar answered Apr 23 '26 15:04

Torbjörn Stabo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!