codeigniter,result()与result_array()

时间:2013-05-12 11:17:51

标签: php codeigniter

我同时使用result()result_array()

通常我喜欢把我的结果作为数组来解释为什么我主要使用result_array()..

但我想知道我应该遵循哪种更好的方法, 哪一个在性能方面更有效?

以下是我在codeigniter查询中讨论的示例

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

或者这应该是更好的方法吗?

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

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

8 个答案:

答案 0 :(得分: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);
    }
}

阵列在技术上更快,但它们不是对象。这取决于您希望在何处使用结果。大多数情况下,数组就足够了。

答案 1 :(得分:6)

为了参考:

// $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()

答案 2 :(得分:4)

result_array()速度更快, result()更容易

答案 3 :(得分:2)

result()返回对象类型数据。 。 。 。 result_array()返回关联数组类型数据。

答案 4 :(得分:1)

返回纯数组比返回一个对象数组要快一些。

答案 5 :(得分:1)

result()是递归的,因为它返回一个std类对象,其中result_array()只返回一个纯数组,因此result_array()可以选择性能。但速度差别很小。

答案 6 :(得分:0)

在我使用result() result_array()时使用JSONresult()来解决问题,如果使用result_array()则没有问题,但是如果使用"Trying to get property of non-object"我会收到错误result()所以我不能深入研究问题所以我只使用JSON如果使用result_array()并使用JSON如果不使用"M 1050000 80 A 40 40 0 1 0 1050000 40"

答案 7 :(得分:0)

result_array() 返回关联数组类型数据。返回纯数组比返回对象数组稍快。 result() 是递归的,因为它返回一个 std 类对象,而 result_array() 只返回一个纯数组,因此 result_array() 将是关于性能的选择。