Welcome Guest, Not a member yet? Register   Sign In
result array keys from columns
#1

[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;
}
#2

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

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




Theme © iAndrew 2016 - Forum software by © MyBB