0

Below is partial of my array

I tried to use the function below to sort it to order by page ascending However it seems rumble around, the page are not in increment state.

I not sure what's wrong with my sorting comparator function (cmp)

function cmp($a, $b) {
    return $a['page'] - $b['page'];
}


usort($chapter_result_array,"cmp");
$chapter_result_array = array_reverse($chapter_result_array);



[11] => Array
    (
        [link] => https://www.mywebsite.com/projects/funny-story/chapter-8-1.1046/
        [page] => 8.1
    )

[12] => Array
    (
        [link] => https://www.mywebsite.com/projects/funny-story/chapter-8-2.1085/
        [page] => 8.2
    )

[13] => Array
    (
        [link] => https://www.mywebsite.com/projects/funny-story/chapter-9-1.1114/
        [page] => 9.1
    )

[14] => Array
    (
        [link] => https://www.mywebsite.com/projects/funny-story/chapter-6-1.890/
        [page] => 6.1
    )

[15] => Array
    (
        [link] => https://www.mywebsite.com/projects/funny-story/chapter-6-2.995/
        [page] => 6.2
    )

[16] => Array
    (
        [link] => https://www.mywebsite.com/projects/funny-story/chapter-7-1.1020/
        [page] => 7.1
    )

[17] => Array
    (
        [link] => https://www.mywebsite.com/projects/funny-story/chapter-5-1.855/
        [page] => 5.1
    )
5
  • not sure, what you want. Its better to give your desire output, so we can clear what you really want. Commented Mar 27, 2016 at 9:05
  • 2
    Note that the manual says that "The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second." Commented Mar 27, 2016 at 9:57
  • @Gralgrathor how do i make it work with "double" Commented Mar 27, 2016 at 10:11
  • 1
    Eh... something like "return ($a < $b) ? -1 : ($a > $b) ? 1 : 0;"? Or any rounding function, if you know what the range of your input is going to be. Commented Mar 27, 2016 at 10:15
  • Once you have it working if you follow @Gralgrathor's advice and you want them in reverse order you can swap -1 with 1 in your function rather than call array_reverse afterwards. Commented Mar 27, 2016 at 15:48

1 Answer 1

0

I guess the pages are not float values but more like "version strings" so you should compare with version compare: Compare two version strings in PHP

It will return you -1, 0 or 1 like usort is intented to be used.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.