2013-05-12 85 views
25

我使用result()result_array()codeigniter,result()vs. result_array()

平時我喜歡讓我的結果作爲數組這就是爲什麼我使用result_array()大多..

,但我想知道哪個是更好的方法,我應該遵循, 它們哪一個更有效用於表現?

這裏是例子中,我在笨談論查詢

​​

或者是這應該是更好的辦法?

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

也現在我在我的通用模型中使用result_array。

回答

26

結果有一個可選的$type參數,該參數決定返回哪種類型的結果。默認情況下($type = "object"),它返回一個對象(result_object())。它可以設置爲"array",然後它將返回一個結果數組,相當於計算result_array()。第三個版本接受一個用作結果對象的自定義類。

從笨代碼:

/** 
* Query result. Acts as a wrapper function for the following functions. 
* 
* @param string $type 'object', 'array' or a custom class name 
* @return array 
*/ 
public function result($type = 'object') 
{ 
    if ($type === 'array') 
    { 
     return $this->result_array(); 
    } 
    elseif ($type === 'object') 
    { 
     return $this->result_object(); 
    } 
    else 
    { 
     return $this->custom_result_object($type); 
    } 
} 

陣列在技術上更快,但他們都沒有對象。這取決於你想在哪裏使用結果。大多數時候,陣列就足夠了。

1

返回純數組比返回對象數組稍快。

1

result()是遞歸的,因爲它返回一個std類對象,其中result_array()只是返回一個純數組,所以result_array()將是關於性能的選擇。儘管速度差別很小。

3

result_array()更快, result()是爲了容易參考,更容易

5

// $query->result_object() === $query->result() 
// returns: 
Array ([0] => stdClass Object ([col_A] => val_1A , [col_B] => val_1B , ...) 
     [0] => stdClass Object ([col_A] => val_2A , [col_B] => val_2B , ...) 
     ... 
    ) 

// $query->result_array() !== $query->result() 
// returns: 
Array ([0] => Array ([col_A] => val_1A , [col_B] => val_1B , ...) 
     [1] => Array ([col_A] => val_2A , [col_B] => val_2B , ...) 
     ... 
    ) 

codeigniter docs for result(), and result_array()

0

在我的遭遇的問題用result()result_array()JSON如果使用result()有我在沒有問題,但它的作品,但如果使用result_array()我得到錯誤"Trying to get property of non-object"這樣的IM,所以我只是用result()如果使用JSON和使用result_array()如果不使用JSON

1

結果()返回Object類型的數據無法搜索到深的問題。 。 。 。 result_array()返回關聯數組類型的數據。

相關問題