I have checked on here and cant find a similar result so if this has been asked I do apologies.
Anyway, I am generating an multi array which has been generated by a nice little class.
Anyway the array comes like this when output:
array(2047) {
[0]=> array(6) {
["name"]=> string(4) "name"
["gamesplayed"] => string(2) "26"
["points"] => string(2) "26"
}
[1]=> array(6) {
["name"]=> string(4) "name"
["gamesplayed"] => string(2) "26"
["points"] => string(2) "42"
}
[2]=> array(6) {
["name"]=> string(4) "name"
["gamesplayed"] => string(2) "26"
["points"] => string(2) "16"
}
// and so on
}
My question is... Is there an easy php function or a neat way on sorting the array into high to low using the points value?
I have had a look at a few php functions but they are just for standard arrays with a single value.
Thanks for any help given :)
UPDATE
I have tried this and it does not sort by points.
Here is the class I am doing it with:
//create sort value
private function sorting_table($a, $b){
return $a['points'] - $b['points'];
}
//sort all users into a table and order the highest to the lowest
public function output_prediction_table($pdo, $year){
//get all uers and put in an array with games played and points.
$getallusers = $pdo->prepare("SELECT userid FROM userpredictions WHERE year=:year");
$getallusers->execute(array(':year' => $year));
//create the multidimentional array
$multidimentional_array = array();
while($fetchallusers = $getallusers->fetch()){
$multidimentional_array[] = array(
'name' => $this->get_username($pdo, $fetchallusers['userid']),
'games' => $this->get_games_played($pdo, $year),
'points' => $this->make_points($pdo, $year, $fetchallusers['userid']),
'userid' => $fetchallusers['userid']
);
}
usort($multidimentional_array, array($this, 'sorting_table'));
$output = '<table class="table-striped">';
$output .= '<tr class="t-h"><td class="t-c">Position</td><td>Username</td><td>Games Played</td><td>Points</td></tr>';
$tablenumber = 1;
foreach($multidimentional_array as $newarray){
$output .= '<tr><td class="t-c">'.$tablenumber.'</td><td><a href="/user/'.$this->sluggify($newarray["name"]).'/'.$newarray["userid"].'/" title="View '.ucwords($newarray["name"]).' Profile">'.ucwords($newarray["name"]).'</a></td><td>'.$newarray["games"].'</td><td>'.$newarray["points"].'</td></tr>';
$tablenumber++;
}
$output .= '</table>';
return $output;
}
I am not getting any errors, its just not sorting with the highest points first to the lowest points last.
Try
usort
You can do something like this:
usort($array, 'sortByPoints');
function sortByOrder($a, $b) {
return $a['points'] - $b['points'];
}
Yo can find more examples here: Sort Multi-dimensional Array by Value
0 comments:
Post a Comment