1

I have my code working perfectly how I want it to, but the problem is my code is sorting by highest value to lowest. Can you help me reverse it so that when I print out the first 10 it is actually the "10 newest" (meaning the lowest duration)?

Thanks so much

function compareStreamDurations($a, $b)
{
     if ($a["duration"] == $b["duration"]) 
     {
        return 0;
     }
     return ($a["duration"] > $b["duration"]) ? -1 : 1;
}

usort($onlineStreams, 'compareStreamDurations');

for ( $i=0; $i<10; $i++ )
{
    echo '<p>', $onlineStreams[$i]["duration"] ,'</p>';
}

The solutions posted below (reversing the sign) are NOT working. I'm doing a print_r of $onlineStreams before and after the usort function call and they are both the same.

2
  • What does your $onlineStreams array look like? Does the "duration" key exist in all array elements? Are the "duration" values numeric? Commented Jul 10, 2011 at 19:01
  • "I'm doing a print_r of $onlineStreams before and after the usort function call and they are both the same?" Does that mean that the sort isn't working in either case, or that the result of the sort is the same whether you compare with > or <? Have you tried checking the return value of usort to make sure that the sort succeeded? Commented Jul 11, 2011 at 2:57

2 Answers 2

3

Just change your greater than to a less than:

return ($a["duration"] < $b["duration"]) ? -1 : 1;
Sign up to request clarification or add additional context in comments.

1 Comment

This did not work when I tested using the for loop (shown above)
0

Try reversing the greater than sign and making it a less than, like this:

function compareStreamDurations($a, $b)
{
     if ($a["duration"] == $b["duration"]) 
     {
        return 0;
     }
     return ($a["duration"] < $b["duration"]) ? -1 : 1;
}

1 Comment

Reversing the > to < did not rearrange properly. It is the same either way

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.