2014-01-08 27 views
1

請認準此查詢:result_array()的ActiveRecord在笨

$this->db->select('users.user_id, user_info.name, user_info.fam ,user_type.type_name '); 
$this->db->from('user_info'); 
$this->db->join('users', 'users.user_id = user_info.user_id'); 
$this->db->join('user_type', 'users.usr_typ_id = user_type.user_type'); 

$data= $this->db->get()->result_array(); 
var_dump($data); 

echo "<hr>"; 

foreach ($data as $row); 
{ 
    echo $row->user_id ."|"; 
    echo $row->name ."|"; 
    echo $row->fam ."|"; 
    echo $row->type_name ."|".'<br>'; 
    echo "<hr>"; 
} 

的結果:

後續代碼var_dump($ data)返回以下行

array(2) { [0]=> array(4) { ["user_id"]=> string(8) "92090001" ["name"]=> string(5) "parsa" ["fam"]=> string(5) "arian" ["type_name"]=> string(13) "Administrator" } [1]=> array(4) { ["user_id"]=> string(8) "92090002" ["name"]=> string(6) "pendar" ["fam"]=> string(6) "pajouh" ["type_name"]=> string(7) "Blogger" } } 

但在「的foreach「部分每行顯示以下錯誤:

A PHP Error was encountered 
Severity: Notice 
Message: Trying to get property of non-object 
Filename: models/user_model.php 
Line Number: 47 

如果有人能幫助我,我會很感激。

+0

什麼行代碼是行47號 – sas

回答

2

在這裏,您使用result_array()。所以它返回帶有stdobject的數組的結果。所以你必須打印下面的類型。

$i=0; 
foreach ($data as $row); 
{ 
    echo $row[$i]->user_id ."|"; 
    echo $row[$i]->name ."|"; 
    echo $row[$i]->fam ."|"; 
    echo $row[$i]->type_name ."|".'<br>'; 
    echo "<hr>"; 
    $i++; 
} 

如果您僅使用result(),那麼您可以使用您的代碼。

foreach ($data as $row); 
{ 
    echo $row->user_id ."|"; 
    echo $row->name ."|"; 
    echo $row->fam ."|"; 
    echo $row->type_name ."|".'<br>'; 
    echo "<hr>"; 
} 
+0

感謝您的關注和答覆。 – Parsaria

2

應使用的result()代替result_array()

$data = $this->db->get()->result(); 

結果()是返回查詢結果作爲對象的數組

result_array()是返回查詢結果作爲純array

或者如果您繼續使用result_array(),則應該更改訪問類型,如下所示:

使用$row['name']而不是$row->name

文檔:http://ellislab.com/codeigniter/user-guide/database/results.html

+0

感謝您的關注和指導。 – Parsaria

1

您需要訪問$row->user_id和其他數據在for循環中作爲這樣"$row['user_id']"

+0

感謝您的關注和答覆。 – Parsaria

0

這些拖車的方式進行測試的,我得到的結果:

第一個是:

$data= $this->db->get()->result(); 

    foreach ($data as $row) 
    { 
    echo $row->user_id ."|"; 
    echo $row->name ."|"; 
    echo $row->fam ."|"; 
    echo $row->type_name ."|".'<br>'; 
    echo "<hr>"; 
    } 

第二個:

$data= $this->db->get()->result_array(); 

foreach ($data as $row) 
{ 
    echo $row['user_id'] ."|"; 
    echo $row['name'] ."|"; 
    echo $row['fam'] ."|"; 
    echo $row['type_name'] ."|".'<br>'; 
    echo "<hr>"; 

}