Reputation: 1
I have a table with 500 results.
I need to order by Players with DESC option, then limit for 10 results and select 5 results aleatory of the 10 with CodeIgniter.
What I have:
public function getServers(){
$this->db2->from('server');
$this->db2->order_by("players", "desc");
$this->db2->limit(5);
$query = $this->db2->get();
if ($query->num_rows() > 0) {
foreach ($query->result() as $row) {
$data[] = $row;
}
return $data;
}
return false;
}
Upvotes: 0
Views: 739
Reputation: 13
Your code should look something like this as suggested by mark above
$my_random_five = array_rand($this->getServers(), 5);
public function getServers(){
$this->db2->from('server');
$this->db2->order_by("players", "desc");
$this->db2->limit(10);
$query = $this->db2->get();
if ($query->num_rows() > 0) {
foreach ($query->result() as $row) {
$data[] = $row;
}
return $data;
}
return false;
}
Upvotes: 0
Reputation: 2156
If I understand you correctly, you want to select the 10 top results in your database, ordered by column players in descending order, and then select 5 of these in random?
Just change one line of your code to:
$this->db2->limit(10);
And then call the method like:
$my_random_five = array_rand($this->getServers(), 5);
Then also consider using http://php.net/manual/en/function.mt-rand.php
Upvotes: 1