【问题标题】:Wordpress error: Warning: count(): Parameter must be an array or an object that implements CountableWordpress 错误:警告:count():参数必须是数组或实现 Countable 的对象
【发布时间】:2020-04-08 16:58:36
【问题描述】:

第一行是问题代码。我不知道如何将该计数更改为可行的值。

if(count($item[2]) > 0){
    if($item[2][0] == 'plane' || $item[2][0] == 'url'){
        if($item[2][0] == 'url'){
            $arr = explode('file/d/',$id);
            $arr1 = explode('/',$arr[1]);
            $id = $arr1[0];
        }
   }
 }
?>

【问题讨论】:

  • 您好,这可能是由于 $item 变量不是可数类型,因此 count() 函数不能用过的。 $item[2] 里面是什么,$item 首先是什么?

标签: php


【解决方案1】:

我相信在某些情况下,$item[2] 返回null 或任何其他不可数的值。从PHP 7 开始,您将无法对未实现可数的对象进行计数。所以你需要先检查它是否是一个数组:

if(is_countable($item[2])){ // you can also use is_array($item[2])
    if(count($item[2]) > 0){
        //rest of your code
    }
}

另一种方法(虽然不是首选)是将您的对象传递给ArrayIterator。这将使它可迭代:

$item_2 = new ArrayIterator($item[2]);
if(count($item_2) > 0){
   //rest of your code
}

【讨论】:

    【解决方案2】:

    试试下面的代码:

    if (is_array($item[2]) || $item[2] instanceof Countable || is_object($item[2])) {
        if(count($item[2]) > 0){
            if($item[2][0] == 'plane' || $item[2][0] == 'url'){
                if($item[2][0] == 'url'){
                    $arr = explode('file/d/',$id);
                    $arr1 = explode('/',$arr[1]);
                    $id = $arr1[0];
                }
            }
        }
    }
    

    查看it

    【讨论】:

      【解决方案3】:

      在 PHP 7.2 中,在尝试计算不可数事物时添加了警告。要修复它,请更改此行:

      if(count($item[2]) > 0){
      

      用这个:

      if(is_array($item[2]) && count($item[2]) > 0){
      

      在 PHP 7.3 中添加了一个新函数 is_countable,专门用于解决 E_WARNING 问题。如果您使用的是 PHP 7.3,那么您可以更改此行:

      if(count($item[2]) > 0){
      

      用这个:

      if(is_countable($item[2]) && count($item[2]) > 0){
      

      【讨论】:

        猜你喜欢
        • 2019-06-20
        • 2018-12-19
        • 1970-01-01
        • 2018-09-10
        • 2019-08-15
        • 2020-01-18
        • 2020-01-27
        • 2019-10-18
        • 2018-10-19
        相关资源
        最近更新 更多