-1

I have been following the instructions for sorting an array by a value in the sub-arrays (from Sort Multi-dimensional Array by Value [duplicate]) but it's just not working for me. See my code below:

$items[] = array("apple", "green", 5.13);
$items[] = array("banana", "green", 5.03);
$items[] = array("banana", "yellow", 6.13);
$items[] = array("apple", "red", 7.13);

function sortByOrder($a, $b) {
    return $a[2] - $b[2];
}

usort($items, 'sortByOrder');

foreach ($items as $item) {
    echo "$item[2] : $item[0] - $item[1]\n";
}

This code returns:

5.13 : apple - green
5.03 : banana - green
6.13 : banana - yellow
7.13 : apple - red

The expected result is this:

5.03 : banana - green
5.13 : apple - green
6.13 : banana - yellow
7.13 : apple - red

So what am I doing wrong?

Community
  • 1
  • 1
Kristian Rafteseth
  • 2,002
  • 5
  • 27
  • 46
  • 1
    Why haven't you follow my advice on your previous question? http://stackoverflow.com/questions/24958027/how-to-order-an-array-by-value-in-sub-array#comment38791521_24958027 – deceze Jul 25 '14 at 14:50
  • 1
    Oh, wow. I didn't didn't click through on the linked question to see that it was by the OP. Wouldn't have answered if I had known that this was a repost of a closed question. – Patrick Q Jul 25 '14 at 14:55
  • Well, how should I have asked the question then? "How to sort by a value in subarray which is not an integer?" Would it have made any difference? – Kristian Rafteseth Jul 25 '14 at 15:11

2 Answers2

3

Replace return $a[2] - $b[2];

With

if($a[2] == $b[2])
{
    return 0;
}
else
{
    return ($a[2] > $b[2]) ? +1 : -1;
}

DEMO

Patrick Q
  • 6,373
  • 2
  • 25
  • 34
  • Dang, I had just typed the exact same thing also found on `http://php.net/manual/en/function.usort.php` good thing I checked new answers before posting – DanceSC Jul 25 '14 at 14:52
0

usort expects the function to return an integer. As you are sorting floats, the values are rounded, which causes the error

In order to get the result you want, you can use phps ceil function to round UP the value:

function sortByOrder($a, $b) {
    return ceil($a[2] - $b[2]);
}
Steve
  • 20,703
  • 5
  • 41
  • 67