-1

I have an array of data comprising a 'customer' and a 'Total'. (example below). It is drawn from two different databases.

I need a way to sort the array, based on the Total field, so that the Largest Total is at the top. But so far every thing I have tried has resulted in it assuming that 5 is larger than 32 [5, 32, 25, 16, 11]

What's the easiest way to achieve this? I tried adding intval() to the strcmp function, but it made no difference?

$arrayName = array();

$arrayName[] = array ('customer' => 'Customer1', 'Total' => 25);
$arrayName[] = array ('customer' => 'Customer2', 'Total' => 16);
$arrayName[] = array ('customer' => 'Customer3', 'Total' => 32);
$arrayName[] = array ('customer' => 'Customer4', 'Total' => 5);
$arrayName[] = array ('customer' => 'Customer5', 'Total' => 11);

print_r($arrayName);
print "</br>";

//Sort the Arrray by Total
function arrSort1($b, $a)
{
    return strcmp($a['Total']), $b['Total']);
};

usort($arrayName, "arrSort1");

print_r($arrayName);
IGGt
  • 2,627
  • 10
  • 42
  • 63

1 Answers1

1

You're comparing by string but you really want to compare by numeric value. Try:

function arrSort1($b, $a)
{
    if ($a['Total'] > $b['Total']) {
        return 1;
    } else if ($a['Total'] < $b['Total']) {
        return -1;
    }
    return 0;
}

The sorted array will look like this:

Array
(
    [0] => Array
        (
            [customer] => Customer3
            [Total] => 32
        )

    [1] => Array
        (
            [customer] => Customer1
            [Total] => 25
        )

    [2] => Array
        (
            [customer] => Customer2
            [Total] => 16
        )

    [3] => Array
        (
            [customer] => Customer5
            [Total] => 11
        )

    [4] => Array
        (
            [customer] => Customer4
            [Total] => 5
        )

)
Jasper
  • 75,717
  • 14
  • 151
  • 146
  • `>` → `-`, `$cmp` needs to return an `int`. – deceze Oct 25 '13 at 15:33
  • @deceze I'm not sure I follow, returning whether or not one is larger than the other sorts the array by `Total` in descending order. You can make it ascending by changing `>` to `<`. – Jasper Oct 25 '13 at 15:36
  • The comparison function must return *"a value `< 0`, `0` or `> 0` depending whether the first value is smaller than, equal to or greater than the second."* A `bool` won't do exactly the same thing. – deceze Oct 25 '13 at 15:37
  • cheers, simply changing the 'return' line has fixed it. – IGGt Oct 25 '13 at 15:38
  • @deceze You're right, now that I think about it I normally use an if/then. I updated the answer. – Jasper Oct 25 '13 at 15:39
  • `$a['Total'] - $b['Total']` will do just fine as well. – deceze Oct 25 '13 at 15:39
  • @deceze yeah nice, now I see what you mean. – Jasper Oct 25 '13 at 15:40