count的次数给出1,如果是空的数组则给出false.为什么?

Jay*_*ran 3 php

我有一个函数只返回一行作为数组.

我给出一个查询作为参数,它只会给出一行.

function getFields($query)
{
    $t =& get_instance(); 
    $ret = $t->db->query($query);
    if(!$ret)return false;
    else if(!$ret->num_rows()) return array();
    else return $ret->row_array();
}
$ret = getFields('query string');
Run Code Online (Sandbox Code Playgroud)

我的想法是......

  1. 如果有错误,那么我可以检查它是否(!$ res)//回显错误
  2. 如果它是空的我可以检查它是否(!count($ res))//没有行
  3. 否则我假设有一行并继续这个过程......

  1. 当出现错误时返回false.在if(count($ ret))中给出1.
  2. 如果我返回空数组,则($ ret)条件失败(给出错误).

//

$ret = getFields('query string');
if(!$fes)jerror('status,0,msg,dberror');        
if(!count($fes))jerror('status,1,msg,no rows');     
// continue execution when there atleast one row.
Run Code Online (Sandbox Code Playgroud)

使用ajax调用此代码.所以我回复了一个json的回复.

为什么count给出1,如果空数组给出错误.

我只想用逻辑条件进行编码,而不是给出更多的关系条件.只是为了减少代码.

我在哪里可以得到所有这些BUGGING的PHP的东西,以便我可以确保我不应该最终做出如上所述的逻辑错误.

BUGGING - 在上面的句子中,我称之为不是bug,但事情让我们烦恼.使我们成为逻辑错误的事情.



我编辑了以下代码以包含以下内容同时我将此作为回复/sf/users/31617071/

我可以这样做,但我仍然想知道为什么上述解释

if($fes===false)jerror();
if(!$fes)jsuccess('status,4');      
Run Code Online (Sandbox Code Playgroud)

Vol*_*erK 6

"为什么算数给1" - 见http://docs.php.net/count:

如果var不是数组[...]将返回1.

"如果空数组给出错误." - 请参阅http://docs.php.net/language.types.boolean#language.types.boolean.casting:

转换为布尔值时,以下值被视为FALSE:
[...]
  • 一个零元素的数组