Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order array list from model function

I am using the Facebook php sdk in my codeigniter application. The code below checks the Facebook friends of the logged in user and matched it against the values on users in the database to check if any of the friends exist as a user of the app.

$friends = $facebook->api('/me/friends');

$temp = array();
 foreach ($friends["data"] as $value) {

            $friendid=$this->upload_model->get_user($value["id"]);

              if (($friendid)) {

                $my_friends=$this->upload_model->get_user($value["id"]);
                $temp[]=$my_friends[0];



            }
$data['top_friends'] = $temp;

This is done using my model in the controller $this->upload_model->get_user($val).

The model:

public function get_user($id)
    {
        $this->db->order_by('points', 'desc'); 
        $this->db->where('id', $id);
        $q=$this->db->get('gamer', 10);
        $data = $q->result_array();
        return $data;
    }

The code returns the friends that exist in the database fine, however I would like to order them in descending order of points (a column in gamers). The model code above should return the top ten friends in terms of points. I want order the gamers by points with the gamer with the most points first.

However, the code doesn't order them, the results are returned and displayed to the view in order of id instead, so in order of how they were entered in the database. How do I order the friends returned so that I can display the top 10 gamers with the highest points in my view. I assumed this would be done in the model query?

My View:

<?php foreach($top_friends as $friend):?>
<p><?php echo $friend['name']; ?></p>
 <?php endforeach; ?>  

Would it matter if it is ordered in the model, or in this case, would I have to somehow order it through the $temp array seeing as it is passed to this array.

But how would I order this from $temp.

How do I do this?

like image 763
Tester Avatar asked Jan 01 '26 03:01

Tester


1 Answers

It's kind of sub array sorting. Try below code:

Add a new function to sort subarray

function sort_points($a, $b) {
  return $b["points"] - $b["points"];
}

Then call usort function with your array:

usort($temp, "sort_points");
like image 101
Kumar V Avatar answered Jan 03 '26 09:01

Kumar V



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!