Welcome Guest, Not a member yet? Register   Sign In
2d array from db into form_dropdown?
#1

[eluser]gscharlemann[/eluser]
What is the easiest way to get a 2D array into a dropdown menu? As an example, I'm trying to create a dropdown that shows the years stored in the DB. The result returned looks like:
Code:
Array ( [0] => Array ( [year] => 2009 ) [1] => Array ( [year] => 2008 ) )
I would like the dropdown menu to be:
Code:
<select name="year">
<option value="all">All</option>
<option value="2008">2008</option>
<option value="2009">2009</option>
</select>

I've tried extracting the values via array_values and then iterating through that and putting it into a new array, but can't quite get it down. Also not sure if that's the most efficient approach to something like this.
#2

[eluser]bretticus[/eluser]
Unless you have some report data bound to those years, I can't see the value in getting a year drop down from the database in the first place, but otherwise...

You just need to build a new array.
Code:
&lt;?php
$query = $this->db->select('year')->get('years');
$years = array();
if ( $query->num_rows() > 0 ) {
  foreach ($query->result() as $row)
  {
   $years[$row->year] = $row->year; //form_dropdown takes an associative array.
         // Associative keys become the option values. The value becomes the option text.
  }
}
// pass to view...
$data['years'] = $years;
// load view...
?&gt;

In your view file...
Code:
&lt;!-- html --&gt;
&lt;?=form_dropdown('years', $years);
&lt;!-- html --&gt;
#3

[eluser]gscharlemann[/eluser]
Fatal error: Call to a member function result() on a non-object

This what I've got. The date information stored in the DB is of date field so my query looks like:
Code:
function get_years()
{
        $this->db->distinct();
        $this->db->select('YEAR(RACE_DATE) as \'year\'');
        return $this->db->get('RACES');
}
the above is in the model file. The result is returned and then I try what you recommended:
Code:
$query = $this->my_model->get_years();
print_r($query);
foreach($query->result() as $row) {
    print_r($row);
    $years[$row->year] = $row->year;
}
$data['years'] = $years;
// call view...etc.

when I print_r on $query, I get the 2D array I had before, which I thought was an object that I could call ->result() on?
#4

[eluser]gscharlemann[/eluser]
it's working now. I'm not sure what I changed, but I no longer get the error and the data I need is there. Thanks for the help.
#5

[eluser]Andres F.[/eluser]
Thanks a lot Bretticus! That did the trick for me. Very much appreciated! This forum is so fantastic!

Regards,
Andres




Theme © iAndrew 2016 - Forum software by © MyBB