简体   繁体   中英

Array sorting doesn't work the way it should be

I'm trying to sort an array,but it doesn't work the way I want to.

My code is as follows.

<?php
$classroom = array("4/10","4/2","4/1","4/11","5/2","1/2","5/1","5/10","5/12");
sort($classroom);
print_r($classroom);
?>

The result is:

Array ( [0] => 1/2 [1] => 4/1 [2] => 4/10 [3] => 4/11 [4] => 4/2 [5] => 5/1 [6] => 5/10 [7] => 5/12 [8] => 5/2 )

I would like to sort it to be:

 1/2,4/1,4/2,4/10,4/11,5/1,5/2,5/10,5/12

I'm quite new to sort functions. Would you please give me an example of using usort?

I presume you are comparing strings in your sort() function. You should first convert your fraction string to float values before comparing them:

function fracstr_to_float($str)    {
    $num = intval(explode("/", $str)[0]);
    $den = intval(explode("/", $str)[1]);
    return $num/$den;
}

NOTE: I assumed that your strings were fractions, not dates.

Coincidentally natsort seems to work:

<?php

$classroom = array("4/10","4/2","4/1","4/11","5/2","1/2","5/1","5/10","5/12");

natsort($classroom);
print_r($classroom);

Prints:

Array
(
    [0] => 1/2
    [1] => 4/1
    [4] => 4/2
    [2] => 4/10
    [3] => 4/11
    [5] => 5/1
    [8] => 5/2
    [6] => 5/10
    [7] => 5/12
) 

Full disclosure: I'm not 100% sure it would work for all use cases, I haven't tested it. Use with caution.

Using usort should work in all cases. It allows us to use a custom function for defining the comparison between array elements. In our custom function we should first convert both elements from fraction to float

function cmp ($a, $b) {
    list($num1, $den1) = explode("/", $a);
    list($num2, $den2) = explode("/", $b);

    $a = ($num1/$den1);
    $b = ($num2/$den2);

    if ($a == $b) {
        return 0;
    }
    return ($a < $b) ? -1 : 1;
}

$classroom = array("4/10","4/2","4/1","4/11","5/2","1/2","5/1","5/10","5/12");

usort($classroom, "cmp");
print_R($classroom);

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