简体   繁体   中英

PHP usort by ascending array value

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
    )

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM