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?

3
  • 1
    Check array_multisort(). Commented May 16, 2013 at 7:41
  • 1
    Read php.net/manual/en/function.array-multisort.php Commented May 16, 2013 at 7:42
  • Do you mean array('name'=>'Robert' , 'total'=>'66')? Commented May 16, 2013 at 7:46

5 Answers 5

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);
Sign up to request clarification or add additional context in comments.

1 Comment

This is what i did and it worked for me.
1

Use Multisort for this

$total = array();
foreach ($array as $key => $row)
{
    $total[$key] = $row['total'];
}
array_multisort($total, SORT_DESC, $array);

Comments

0

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

Comments

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

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.