CodeIgniter Forums

Full Version: result array keys from columns
You're currently viewing a stripped down version of our content. View the full version with proper formatting.

El Forum

[eluser]Unknown[/eluser]
I just wanted to share a change I made on the result_array db function. It will let you specify a column to use as a key in the array that it returns:
Code:
$this->db->query($sql)->result_array('id');
In that example it would use the id column as the array key, which I think makes it easier to work with in some situations.

Here's the modified function from DB_result.php
Code:
function result_array($key = NULL)
{
    if (count($this->result_array) > 0)
    {
        return $this->result_array;
    }

    // In the event that query caching is on the result_id variable
    // will return FALSE since there isn't a valid SQL resource so
    // we'll simply return an empty array.
    if ($this->result_id === FALSE OR $this->num_rows() == 0)
    {
        return array();
    }

    $this->_data_seek(0);            
    while ($row = $this->_fetch_assoc())
    {
        if ( ! is_null($key) )
            $this->result_array[$row[$key]] = $row;
        else
            $this->result_array[] = $row;
    }
    
    return $this->result_array;
}

El Forum

[eluser]cyang[/eluser]
Cool beans, great for generating form dropdowns!

El Forum

[eluser]hyperfire[/eluser]
A must have Smile