0

I am using usort to sort my arrays. I have an array that contains warranty dates. And a sort function that sorts it. However the problem I am having is that not all of the items in the array have a warranty. I want to sort the array but always placing the ones with no date at the bottom.

function warrantyA($a, $b){
    if($a->Warranty == "Available" and $b->Warranty == "Available"){
        $a = explode('/', $a->WarrantyDescription);
        $b = explode('/', $b->WarrantyDescription);

        $today = date("d-m-Y");

        $diffa = abs(strtotime($a[0]) - strtotime($today));
        $diffb = abs(strtotime($b[0]) - strtotime($today));

        $a = floor($diffa / 86400 / 30 );
        $b =  floor($diffb / 86400 / 30 );
        return $a - $b;
    }
}

The above is the code I have now.It does not work the way I want it to. Each object has warranty and warranty description. If there is a warranty then it will say "Avaiable".

The code take the warranty and compares it to today's date to determine the amount of months left on the warranty and I want to sort it by that number.

How can I make this functional so that any item that has no warranty is placed at the bottom of the array?

4

1 回答 1

2

Here is a bit of a trick: Turn the results of $a->Warranty=="Available" and $b->Warranty == "Available" into ints ( will be zero or one), then do a similar subtraction to what you have. If a has a warranty and b doesn't, this will be 1 - 0, or a is greater. If a does not but b does, it will return -1, and 0 if they both don't.

$a_has = (int) $a->Warranty == "Available";
$b_has = (int) $b->Warranty == "Available";
if($a_has and $b_has){
    // keep your code here
}

return $a_has - $b_has;
于 2012-07-10T16:11:30.630 回答