2014-01-10 25 views
0

欲一個MySQL行轉換成與屬性=>值的對象笨轉換MySQL的行到對象

例如

$query = "SELECT * FROM blah..."; 
if($query->num_rows() > 0) 
{ 
    foreach($query->result_array() as $row) 
    { 
     $notification = new stdClass(); 
     //this is where I don't know what to do 
     for every coloumn 
      $notification->coloumn_name = value at that coloumn; 
     //end of cluelessness 
     return $notification; 
    } 
} 

回答

0

使用$query->result()在你的foreach循環..

This function returns the query result as an array of objects, or an empty array on failure. 

Also see this欲瞭解更多信息...

0

使用$ query-> result()。 這將一次返回一行,直到用完結果中的行對象。

foreach ($query->result() as $row) 
{ 
    // Use $row as an object 
    // echo $row->name; 
} 
1

可以使用

$query->result();
它總是返回一個stdClass的對象數組..

1

試試這個代碼

$this->db->select('in_page_id,st_page_name,st_page_content'); 
$this->db->from('tbl_page_master'); 
$query = $this->db->get(); 

if($query->num_rows()>0) 
{ 
    foreach($query->result() as $Row) 
    { 
     $arrCMS[$Row->in_page_id] = array('cms_id'  => $Row->in_page_id, 
               'cms_title' => $Row->st_page_name, 
               'cms_details' => $Row->st_page_content 
              ); 
    } 
} 
return $arrCMS; 

完整的動態功能可以按如下方式寫入。

function selectAll($table) 
{ 
    $arrData = array(); 

    $this->db->select('*'); 
    $this->db->from($table); 
    $query = $this->db->get(); 

    if($query->num_rows()>0) 
    { 
     foreach($query->result() as $Row) 
     { 
      foreach($Row as $key=>$value) 
      { 
       $arr_element[$key] = $value; 
      } 
      $arrData[] = $arr_element; 
     } 
    } 
    return $arrData; 
}