Reputation: 2967
I have the following array:
$data=array(
'Points'=>$points,'Name'=>$row['Name'], 'Phone'=>$row['phone']
);
This resides in a for each loop in my Codeigniter controller index function:
public function index(){
$query=$this->My_model->get_data();
foreach ($query as $row)
{
$data=array(
'Points'=>$points,'Name'=>$row['Name'], 'Phone'=>$row['phone']
);
}
}
Currently if I print_r on $data it would produce:
Array ( [Points] => 500 [Name] => Dave Laus )
Array ( [Points] => 1200 [Name] => John Smith )
Array ( [Points] => 700 [Name] => Jason Smithsonian )
However I would like to sort/order this so that the user with the highest points showing first like this:
Array ( [Points] => 1200 [Name] => John Smith )
Array ( [Points] => 700 [Name] => Jason Smithsonian )
Array ( [Points] => 500 [Name] => Dave Laus )
I want to sort the array by the "Points" key, so that the user with the highest points appear first. I want to re order the array to show from highest to lowest points.
I have tried usort and arsort and ksort. I haven't gotten it to work.
How do I do this?
I tried this in my controller, but it's doesn't work, errors instead:
public function index(){
$query=$this->My_model->get_data();
foreach ($query as $row)
{
$data=array(
array('Points'=>$points,'Name'=>$row['Name'], 'Phone'=>$row['phone']),
);
function cmp ($a, $b) {
return $a['Points'] < $b['Points'] ? 1 : -1;
}
usort($data, "cmp");
print_r($data);
//I also tried usort($leaders, array('home', 'cmp')); whcih gave no errors, but was the same result as before, not ordered
}
}
Upvotes: 0
Views: 1174
Reputation: 2498
Following function will allow you to sort the given array using specific field along with direction (asc or desc). It accepts parameters as
// $field = field / key for sorting
// $array = array to sort
// $direction = ascending or descending sort direction (default is ascending)
function sortBy($field, &$array, $direction = 'asc')
{
usort($array, create_function( '$a, $b', '
$a = $a["' . $field . '"];
$b = $b["' . $field . '"];
if ($a == $b) {
return 0;
}
return ($a ' . ($direction == 'desc' ? '>' : '<') .' $b) ? -1 : 1;'));
return true;
}
Now use following code to actually sort the array
sortBy('Points', $data, 'desc'); // sorts in descending order for value of key Points
sortBy('Name', $data, 'asc'); // sorts in ascending order for value of key Name
I suggest you take a look at following link http://phpave.com/sorting-associative-array-specific-key/
Upvotes: 0
Reputation: 7447
Try this:
function cmp ($a, $b) {
return $a['Points'] < $b['Points'] ? 1 : -1;
}
usort($data, "cmp");
Upvotes: 2