Change order of foreach loop? - Printable Version +- CodeIgniter Forums (https://forum.codeigniter.com) +-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20) +--- Forum: Archived Development & Programming (https://forum.codeigniter.com/forumdisplay.php?fid=23) +--- Thread: Change order of foreach loop? (/showthread.php?tid=11863) |
Change order of foreach loop? - El Forum - 09-25-2008 [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 Change order of foreach loop? - El Forum - 09-25-2008 [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'); Change order of foreach loop? - El Forum - 09-25-2008 [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? Change order of foreach loop? - El Forum - 09-25-2008 [eluser]LifeSteala[/eluser] I thought it was orderby() not order_by() (Note no underscore). Change order of foreach loop? - El Forum - 09-25-2008 [eluser]slaction[/eluser] From the user guide.... Quote:Note: order_by() was formerly known as orderby(), which has been deprecated. Change order of foreach loop? - El Forum - 09-26-2008 [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) { That's obviously less efficient than ordering in the DB, but still works. Useful way to do it sometimes Change order of foreach loop? - El Forum - 09-26-2008 [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. Change order of foreach loop? - El Forum - 09-26-2008 [eluser]slaction[/eluser] Dready, That worked! Thanks a lot for the replies! |