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