2014-02-18 15 views
1

http://ellislab.com/codeigniter/user-guide/database/results.html的Codeigniter查詢的所有示例中,我發現必須知道該字段的名稱以獲取其值。按數字索引獲取ASSOC數組值

$query = $this->db->query("SELECT title,name,body FROM table"); 

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

例如,如果我想獲得title,我將執行row->title。有沒有辦法使用索引獲得title$row[0]

+0

這是你不能使用一個對象作爲對象陣列。 – guybennet

回答

3

使用result_array函數返回的查詢結果作爲一個純粹的陣列

$query = $this->db->query("SELECT title,name,body FROM table"); 
    $result = $query->result_array(); 
    foreach($result as $res){ 
     echo $res['title']; 
     echo $res['name']; 
     echo $res['body']; 
    } 
如果要通過索引來訪問,然後用array_values

$result = $query->result_array(); 
    foreach($result as $res){ 
     $r = array_values($res); 
     echo $r[0]; 
     echo $r[1]; 
     echo $r[2]; 
    } 
+0

-1 OP希望通過數字索引獲取值,而不是通過鍵名。 –

0
<?php 
    $result = $subject_code->result_array(); 
    foreach($result as $res){ 
    $r = array_values($res); 
    print_r($r); 
    } 
?> 
I applied the above code but in o/p index of each value is comming 0 
o/p- Array ([0] => 201) Array ([0] => 202) Array ([0] => 203) Array ([0] => 204) Array ([0] => 205)