CodeIgniter Forums
result array keys from columns - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forum-20.html)
+--- Forum: Archived Libraries & Helpers (https://forum.codeigniter.com/forum-22.html)
+--- Thread: result array keys from columns (/thread-9197.html)



result array keys from columns - El Forum - 06-16-2008

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



result array keys from columns - El Forum - 08-25-2008

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


result array keys from columns - El Forum - 12-10-2008

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