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

[eluser]slaction[/eluser]
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.

thanks
#2

[eluser]Developer13[/eluser]
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');
#3

[eluser]slaction[/eluser]
Here is my code for returning the database info

Code:
$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?
#4

[eluser]LifeSteala[/eluser]
I thought it was orderby() not order_by() (Note no underscore). Smile
#5

[eluser]slaction[/eluser]
From the user guide....
Quote:Note: order_by() was formerly known as orderby(), which has been deprecated.
#6

[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:

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

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

[eluser]Dready[/eluser]
Hello,

you must not add order by at the end of your active record query. Try :
Code:
$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.
#8

[eluser]slaction[/eluser]
Dready,

That worked!

Thanks a lot for the replies!




Theme © iAndrew 2016 - Forum software by © MyBB