简体   繁体   English

CodeIgniter - 数据库结果数组但只有一行

[英]CodeIgniter - database result array but only one row

I'm looking for a way to return an array from the database query, but only for the first row. 我正在寻找一种从数据库查询返回数组的方法,但仅限于第一行。 I'd prefer not to use objects.. 我不想使用对象..

My current solution: 我目前的解决方案

//Gather
$data = $this->db->from('view')->where('alias', $alias)->get()->result_array();

//Collect the first row only
$data = $data[0];

Which is pretty ugly to be honest. 说实话,这非常难看。 As said, I'd prefer to not use objects. 如上所述,我宁愿不使用对象。

Use the row() method instead: 改为使用row()方法:

$data = $this->db->from('view')->where('alias', $alias)->get()->row();

[Oh, you don't want to use objects. [哦,你不想使用物体。 row_array() then. 然后是row_array() But consider objects.] 但考虑对象。]

You can do this: 你可以这样做:

$data = $this->db->from('view')->where('alias', $alias)->get()->row_array();

This does the same as minitech's answer, only it returns an array (like you want) instead of an object. 这和minitech的答案一样,只返回一个数组(就像你想要的那样)而不是一个对象。

You can use the row_array() function to grab data from a single row. 您可以使用row_array()函数从单行中获取数据。 Specify that row as the parameter. 将该行指定为参数。

For example, to get the first row of your result, do this: 例如,要获取结果的第一行,请执行以下操作:

$this->db->from('view')->where('alias', $alias)->get()->result_array(0);

If you want to get only first row as an array you can use this code too: 如果您只想将第一行作为数组,您也可以使用此代码:

$data = $this->db->from('view')->where('alias', $alias)->get()->first_row('array');

But if you really want to get only 1 result, allways use select('TOP 1 ....') because this method improves your query returning time performance. 但是如果你真的只想获得1个结果,那么总是使用select('TOP 1 ....'),因为这种方法可以提高你的查询返回时间性能。 When you use get() directly, it will try to return whole data and not only first row. 当你直接使用get()时,它会尝试返回整个数据,而不仅仅是第一行。 And then it shows what you want (first row). 然后它显示了你想要的东西(第一排)。 But if you use TOP 1 method; 但是如果你使用TOP 1方法; it's the best. 这是最好的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM