0

I am trying to make a top ten list of games for my website. I have an associative array that contains all the information about the games on my site.

$games = array();
$games[] = array(
"title" => 'Disaster will strike 2',
"link_name" => 'disaster-will-strike-2',
"id" => 1,
"desc" => 'Create earthquakes, launch fireballs and cause other crazy disasters to destroy all the eggs in each level.',
"cat" => 'Puzzle',
"img_src" => 'img/disaster_will_strike_2.png',
"play_count" => 0
);

Each game has a key called "play_count" that will go up each time a user goes on to play that game. I would like to list the ten games with the highest play count from highest to lowest. I have know idea how to this. I have tried using for loops, nested for loops, foreach loops and I have no idea what I'm doing wrong. Could anybody help me with this?

Chris Laplante
  • 28,157
  • 16
  • 93
  • 131
John McDonald
  • 69
  • 1
  • 10

2 Answers2

2

You can use usort() to sort each entry by the play_count key. usort means "user-defined sort"; it lets you specify a custom comparison function.

Then use array_slice() to take a max of 10 elements from the sorted array.

Example:

function sorter($a, $b){
    if ($a->play_count == $b->play_count) { 
        return 0;   
    }

    return $a->play_count < $b->play_count ? -1 : 1;
}

// Sort in place
usort($games, "sorter");

$top_ten = array_slice($games, 0, 10);

The call to array_slice is saying: "I want 10 elements from the array starting at index 0." If less than 10 elements exist, the function is smart enough to only return those and not throw an error.

Chris Laplante
  • 28,157
  • 16
  • 93
  • 131
0

An approach would be following

$games = array(
    array('title' => 'game_1', 'play_count' => 5),
    array('title' => 'game_2', 'play_count' => 4),
    array('title' => 'game_3', 'play_count' => 1),
    array('title' => 'game_4', 'play_count' => 4),
    array('title' => 'game_5', 'play_count' => 3),
    array('title' => 'game_6', 'play_count' => 9),
    array('title' => 'game_7', 'play_count' => 9),
    array('title' => 'game_8', 'play_count' => 11),
    array('title' => 'game_9', 'play_count' => 14),
    array('title' => 'game_10', 'play_count' => 12),
    array('title' => 'game_11', 'play_count' => 5),
    array('title' => 'game_12', 'play_count' => 7),
);

function custom_sort($a, $b) {
    return $a['play_count'] < $b['play_count'];
}

usort($games, 'custom_sort');
$top = array_slice($games, 0, 10);
Davit
  • 1,340
  • 5
  • 20
  • 47