【问题标题】:Variable is an array but not countable?变量是数组但不可数?
【发布时间】:2020-02-01 01:45:10
【问题描述】:

我正在将我们的 Codeigniter (v. 3.1.11) 站点从 php 5.6 升级到 php 7.2(目前在我的 Mac 上的 localhost 上运行)。慢慢地,我找到了所有使用 count() 的实例并更正它们。我的理解是数组是可数的,但我似乎无法计算 Codeigniter 的 result_array() 函数在数据库调用后返回的数组......

我的控制器的以下部分

    $reviews = $this->reviews_model->review_details($productname);
    echo "Variable is type: ".gettype($reviews);
    if (count($reviews >=1)) {
        $myreview=$reviews[0];
    } else {
        $myreview=0;
    }
    return $myreview;

在我的模型中调用这个函数(请注意,我只是为了确定而回显变量类型!)

    function review_details($pagename) {
    $r = false;
    $sql = "select Reviews.*, ReviewItemLink.Item as Product, ReviewItemLink.* from Reviews LEFT JOIN ReviewItemLink ON Reviews.ReviewItemID=ReviewItemLink.ReviewItemID where pagename=? AND ReviewActive = 1 ORDER BY Date DESC";
    $query = $this->db->query($sql, $pagename);
    if ($query->num_rows() > 0):
        $r = $query->result_array();
    endif;
    return $r;
}

即使变量是一个数组

Variable is type: array

我现在仍然收到了,哦,如此熟悉的警告信息:

Severity: Warning
Message: count(): Parameter must be an array or an object that implements Countable
Filename: controllers/Software.php
Line Number: 1005

Backtrace:

File: /Users/juner/Sites/html/application/controllers/Software.php
Line: 1005
Function: _error_handler
File: /Users/juner/Sites/html/application/controllers/Software.php
Line: 75
Function: _get_my_review

File: /Users/juner/Sites/html/index.php
Line: 324
Function: require_once

是否存在不可数的数组类型?任何建议/想法都会很有帮助!

【问题讨论】:

    标签: php codeigniter count countable


    【解决方案1】:

    这部分不正确(错字?):

    if (count($reviews >=1)) {
        $myreview=$reviews[0];
    } else {
        $myreview=0;
    }
    

    您正在将布尔值传递给 count 函数。 count($reviews >=1) 转为count(true);这就是你收到警告的原因。

    if (count($reviews >=1)) { 应该是if (count($reviews) >=1 ) {

    【讨论】:

    • 哦——天哪!多么愚蠢的错误。是的 - 更正允许它被计算在内。但这确实让我想知道这在 5.6 上多年来是如何工作的!
    • 在 PHP 5.6 中,count(true) 给你1,因为type coercion。因此,在您的情况下,它返回 1 并允许循环继续。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-28
    • 1970-01-01
    • 1970-01-01
    • 2012-09-05
    • 2017-12-27
    • 1970-01-01
    相关资源
    最近更新 更多