-1

my array looks like this:

array(3) { 
[1]=> array(2) { 
    ["username"]=> string(8) "bob123" 
    ["percent"]=> int(100) 
} 
[2]=> array(2) { 
    ["username"]=> string(13) "bryan123" 
    ["percent"]=> int(0) 
} 
[3]=> array(2) { 
    ["username"]=> string(8) "jim123" 
    ["percent"]=> int(0) 
} 
}

I would like to sort by the percent field inside of my array titled $friends, how would I do this?

  • So what code have you created to attempt to solve this issue? – Giacomo1968 Jan 05 '14 at 08:48
  • possible duplicate of [Reference: all basic ways to sort arrays and data in PHP](http://stackoverflow.com/questions/17364127/reference-all-basic-ways-to-sort-arrays-and-data-in-php) – deceze Jan 05 '14 at 08:48

2 Answers2

3

Write a comparison function that comapares two elements according to your preferred order and pass that function along with the array to usort.

Oswald
  • 31,254
  • 3
  • 43
  • 68
0

Array

$array = array(
  array("username"=> "bob123", "percent"=> 10),
  array("username"=> "bob123", "percent"=> 9),
  array("username"=> "bob123", "percent"=> 9)
  );

Function callback for usort

function callb($a, $b){
  if($a['percent'] == $b['percent']){
    return 0;
  }
  return ($a['percent'] > $b['percent'])? +1:-1;  
}

Usage

usort($array,"callb");
 print_r($array);

https://eval.in/85986

Sibiraj PR
  • 1,481
  • 1
  • 10
  • 25