Welcome Guest, Not a member yet? Register   Sign In
Change order of foreach loop?

I am using the foreach loop code from the video tutorial to show the rows in my database. The problem is I want to show the newest rows on top but the loop currently just adds the new rows to the bottom of the list.

How would I go about changing the order of the items. I looked at the order_by() part of active record, but I'm already using get_where() and I didn't know how to add order_by on top off my get_where.

Any help would be great.


Couple of ways you could achieve this.

1 - Using get_where() and order_by():

$this->db->order_by('date DESC');

$query = $this->db->get_where('table', array('this' => $that));

2 - Using plain old get() and order_by() with where():

$this->db->order_by('date DESC');

$this->db->where('this', $that);

$query = $this->db->get('table');

Here is my code for returning the database info

$data['query'] = $this->db->get_where('listings', array('isactive' => 1));

I've tried adding order_by() to the end of the code but I get a fatal error.

Any ideas?

I thought it was orderby() not order_by() (Note no underscore). Smile

From the user guide....
Quote:Note: order_by() was formerly known as orderby(), which has been deprecated.

[eluser]Phil Sturgeon[/eluser]
They both work fine for now.

If this is a one-off and you dont want to modify the model, you can use ksort.

Create an array of your users with their join date as the key like so:

foreach($this->users_m->getUsers() as $user) {
    $users[$user->join_date.$user->name] = $user;

That's obviously less efficient than ordering in the DB, but still works. Useful way to do it sometimes Smile


you must not add order by at the end of your active record query. Try :
$data['query'] = $this->db->order_by('date','desc')->get_where('listings', array('isactive' => 1));

In this example I suppose you have a "date" column in your table.


That worked!

Thanks a lot for the replies!

Theme © iAndrew 2016 - Forum software by © MyBB