문제

I've got a problem processing longer PHP arrays through usort() function. I want to sort an array with 40-50 elements like "1.1","2.3","1.1.2","3.1",30,"3.10"... If I proceed only a few elements, everything works fine. But if I have an array of 40 elements, the function is simply too slow - so slow, that it even overrides the 90 sec timeout...

My code:

function mySort($a,$b) {
    $a_arr = explode(".",$a);
    $b_arr = explode(".",$b);

    if ($a_arr[0] < $b_arr[0]) {return -1;break;}
    if ($a_arr[0] > $b_arr[0]) {return 1;break;}

    for($i=0;$a_arr[$i]==$b_arr[$i];$i++){
        if ($a_arr[$i+1] < $b_arr[$i+1]) {return -1;break;}
        if ($a_arr[$i+1] > $b_arr[$i+1]) {return 1;break;}
    }
  }

$sort_array = array("1.1","2.3","1.1.2","3.1","30","3.10"); //example, I take this data from the database

usort($sort_array,"mySort");

...Could anyone help, please? Is it possible to solve this? Any help would be greatly appreciated.

Thanks in advance.

도움이 되었습니까?

해결책 2

Your loop does not exit when there are values in the array which are equal. Add a return 0 clause somewhere to signify when two elements of the array are equal.

That should probably happen when you are out of elements for any of either list (a, b). Because otherwise you will get notices about accessing array-indexes which do not exist. (Your sample gives one such notice)

다른 팁

function mySort($a,$b) {
    return version_compare($a,$b);
}

$sort_array = array("1.1","2.3","1.1.2","3.1","30","3.10");    
usort($sort_array,"mySort");

var_dump($sort_array);

or even simply

$sort_array = array("1.1","2.3","1.1.2","3.1","30","3.10");    
usort($sort_array,"version_compare");

var_dump($sort_array);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top