我用两个result()
和result_array()
.
通常我喜欢把我的结果作为数组,这就是为什么我主要使用result_array()
但我想知道哪种更好的方法应该遵循哪一种,哪种方法在性能方面更有效?
这是我在codeigniter查询中讨论的示例
$query = $this->db->get();
$result = $query->result_array();
Run Code Online (Sandbox Code Playgroud)
或者这应该是更好的方法?
$query = $this->db->get();
$result = $query->result();
Run Code Online (Sandbox Code Playgroud)
现在我也在我的通用模型中使用result_array.
Whi*_*ity 32
Result有一个可选$type
参数,用于决定返回的结果类型.默认情况下($type = "object"
),它返回一个对象(result_object()
).它可以设置为"array"
,然后它将返回一个结果数组,相当于caling result_array()
.第三个版本接受用作结果对象的自定义类.
CodeIgniter的代码:
/**
* 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);
}
}
Run Code Online (Sandbox Code Playgroud)
数组在技术上更快,但它们不是对象.这取决于您希望在何处使用结果.大多数情况下,阵列就足够了.
为了参考:
// $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 , ... )
...
)
Run Code Online (Sandbox Code Playgroud)
resultigniter docs for result()和result_array()