2

So I have an array:

$array = (
    array('name' => 'John' , 'total' => '33'),
    array('name' => 'Robert' , 'total' =>  '66'),
    array('name' => 'John' , 'total' => '22'),
)

I want to sort the arrays by the total.

So the output would be:

$array = (
    array('name' => 'Robert' , 'total' =>  '66')
    array('name' => 'John ' , 'total' => '33')
    array('name' => 'John' , 'total' => '22')
)

How can I do this?

Prasanth Bendra
  • 31,145
  • 9
  • 53
  • 73
user2385273
  • 45
  • 1
  • 1
  • 6

5 Answers5

1

Use Multisort for this

$total = array();
foreach ($array as $key => $row)
{
    $total[$key] = $row['total'];
}
array_multisort($total, SORT_DESC, $array);
chandresh_cool
  • 11,753
  • 3
  • 30
  • 45
1

use array_multisort method

$arr = array(
    array('name' => 'John' , 'total' => '33'),
    array('name' => 'Robert' , 'total' =>  '66'),
    array('name' => 'John' , 'total' => '22'),
);

$total = array();
foreach ($arr as $key => $row)
{
    $total[$key] = $row['total'];
}
array_multisort($total, SORT_DESC, $arr);
Waqar Alamgir
  • 9,828
  • 4
  • 30
  • 36
0

No, I think you should better use arsort(). http://www.php.net/manual/en/function.arsort.php

Matheno
  • 4,112
  • 6
  • 36
  • 53
0
function totalDescSort($item1, $item2)
{
    if ($item1['total'] == $item2['total']) return 0;
    return ($item1['total'] < $item2['total']) ? 1 : -1;
}
usort($array,'totalDescSort');

From here: https://stackoverflow.com/a/1597788/623400

Community
  • 1
  • 1
David Müller
  • 5,291
  • 2
  • 29
  • 33
0

I think you can use array_multisort() to order your array elements in a DESCENDING order:

$array = array(

     array('name' => 'John', 'total' => '33'),
     array('name' => 'Robert', 'total' =>  '66'),
     array('name' => 'John', 'total' => '22')

);

array_multisort($array, SORT_DESC);
var_dump($array);

this will output

array(3) {
  [0]=>
  array(2) {
    ["name"]=>
    string(6) "Robert"
    ["total"]=>
    string(2) "66"
  }
  [1]=>
  array(2) {
    ["name"]=>
    string(4) "John"
    ["total"]=>
    string(2) "33"
  }
  [2]=>
  array(2) {
    ["name"]=>
    string(4) "John"
    ["total"]=>
    string(2) "22"
  }
}

DEMO

Fabio
  • 23,183
  • 12
  • 55
  • 64