Welcome Guest, Not a member yet? Register   Sign In
db result_array to dropdown
#1

[eluser]louisc[/eluser]
Hi everyone, I am having problems with the way codeigniter returns the result_array array.

Example:

Model:
Code:
public function get_titles()
    {
        $query = $this->db->get('lu_titles'); // id and value for dropdown
        return $query->result_array();
    {

View:
Code:
$db_results = $this->lookup_model->get_titles();

Which in theory would work great, but it doesn't!

Please help me, it returns a 2d array and this messes everything up.

Please be patient, I am new to codeigniter and did google.
#2

[eluser]Piter[/eluser]
Code:
public function get_titles ()
{
$query = $this -> db -> get ( 'lu_titles' ); // id and value for dropdown
return $query -> result_array ();
}

You have {instead of }in the method
#3

[eluser]louisc[/eluser]
please explain what you just said, I do not understand.
#4

[eluser]C. Jiménez[/eluser]
You can pre-process your result array in model to send expected data to your controller.
Code:
public function get_titles ()
{
$query = $this -> db -> get ( 'lu_titles' ); // id and value for dropdown
$raw_data =  $query -> result_array ();
foreach ($raw_data as $line){
             $dropdown_array[$line['name']] = $line['id']
             }
return $dropdown_array;
}

of course, you must add to this code all your checks about getting false query, 0 rows, and things like that.
#5

[eluser]Piter[/eluser]
My helper to drop_down Smile

Code:
<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* array_to_select to from_dropdown helper
*
* @access    public
* @param    Array data
* @param    String Key
* @param    String Value      
* @param    Bool Frst empty
* @return    Array
*/
    
if ( ! function_exists('array_to_select'))
{
    function array_to_select($array, $key, $value, $first_empty = FALSE)
    {
        
        $result = Array();
        if($first_empty)
        {
            $result['0'] = '-------------';
        }
        
        if(is_array($array))
        {
            foreach($array as $item)
            {
                  $result[$item[$key]] = $item[$value];    
            }
        }
        
        return $result;
    }
}

Code:
echo form_dropdown('dropdown', array_to_select($result_array, 'id', 'name'), set_value('dropdown'));
#6

[eluser]louisc[/eluser]
Thanks a lot! Will check it out. Appreciate the replies.




Theme © iAndrew 2016 - Forum software by © MyBB