0

I'm looking to sort the results of a query in the controller, "after" it is returned from the model, here is what im trying:

$query = $this->user->get_all_users();
foreach($query as $user){
    // dynamically according to my projects' logic 
    // assigns a grade to  each user
    $user->grade = assign_a_grade_to_user() 
}

what im looking to do is , the results in $query should be sorted according to the grade a student has , and then pass that sorted $query to my view to print

any suggestions or idea to get this ?

NOTE : no issues if we use another temporary variables or data structures like we can store the sorted results in some other variable too

1
  • the simple answer is use order by in he query and you dont have to do anything else Commented Aug 19, 2012 at 19:14

1 Answer 1

1

This should do:

  function cmp( $a, $b )
    { 
      if(  $a->grade==  $b->grade){ return 0 ; } 
      return ($a->grade< $b->grade) ? -1 : 1;
    } 

    $sortedArray=usort($query ,'cmp');

So your code should look like:

$query = $this->user->get_all_users();
foreach($query as $user){
    // assigns a grade to  each user
    $user->grade = assign_a_grade_to_user() 
}

 $sortedArray=usort($query ,'cmp');
$data['users']=$query;
$this->load->view('home',$data);
Sign up to request clarification or add additional context in comments.

6 Comments

forgive me if its too dumb , but how do i call this cmp function ? say the code snippet i wrote is in my index() , do i pass $query to cmp ?
The usort function will handle that (as it recieves the second parameter function name) and returns the sorted array of objects.
is there any way in which i can store my result in the object form , like when i return the results from my model , its return $query->result() is there i can get result in the same form from usort or something similar ?
the usort function recieves an array as param and returns an array. I don t get your question
i want to convert the resulting array to a object , ie i want to merge back the result $user
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.