Codeigniter/PHP: Format db query as an array

淺唱寂寞╮ 提交于 2021-02-15 10:37:39

问题


    $this->db->select('id, user_id')->from('be_users')->where('id',$user_id);
    $data['user_individual'] = $this->db->get();

If this is my db query, how do I get an array of one db row...

ie. I want to do something like $data['user_individual']['id']->format_as_array...


回答1:


CodeIgniter provides several methods to perform on query results.

See here: https://codeigniter.com/user_guide/database/results.html

result() returns an array of PHP objects.

row() returns a single PHP object for that row.

result_array() returns an array of arrays.

row_array() returns a single array for that row.

row() and row_array() optionally take a parameter which is the number of the row you'd like to return.

Beyond this, it's difficult to tell exactly what you're asking for. You should be able to get your data out exactly as you like with these methods.

Edit:

Incidentally, the way to access these methods is through the query object returned from the $this->db->get() call:

$query = $this->db->get();

$rows = $query->result(); //array of objects
$rows_array = $query->result_array(); //array of arrays
$row = $query->row(); //single object
$row_array = $query->row_array(); //single array



回答2:


When you use $this->db->get(); you can use $this->db->result(); which returns an arrayobject.

$query = $this->db->get('table_name');

foreach ($query->result() as $row)
{
    echo $row->title;
}

See: http://codeigniter.com/user_guide/database/results.html for details on how to obtain resultsets from the database.




回答3:


Instead of $ this-> db-> get () use $ this-> db-> row_array ();

$this->db->select('id, user_id')->from('be_users')->where('id',$user_id);
$data['user_individual'] = $this->db->row_array();



回答4:


/** * format_database_array * * Lets you format the database object data to array

  • @access public
  • @param String $db_object : database query object
  • @return String : Return array with data */

if ( ! function_exists('format_database_array')) {

    function format_database_array($db_object)
{
    $db_array = array();

    if($db_object-> num_rows >0)
    {
        foreach ($db_object->result_array() as $row)
        {
            foreach ($row as $key => $value)
            {
                $db_array[$key] = $value;
            }
        }
    }

    return $db_array;
}

}



来源:https://stackoverflow.com/questions/4610276/codeigniter-php-format-db-query-as-an-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!