Wordpress 错误:警告:count():参数必须是数组或实现 Countable 的对象

第一行是问题代码。我不知道如何将计数更改为可以工作的东西。


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];

        }

   }

 }

?>


蓝山帝景
浏览 159回答 3
3回答

慕侠2389804

在 PHP7.2中,在尝试计算不可数事物时添加了警告。要使其修复更改此行:if(count($item[2]) > 0){有了这个:if(is_array($item[2]) && count($item[2]) > 0){在 PHP7.3中添加了一个新函数is_countable,专门用于解决该E_WARNING问题。如果您使用的是 PHP 7.3,那么您可以更改此行:if(count($item[2]) > 0){有了这个:if(is_countable($item[2]) && count($item[2]) > 0){

千巷猫影

试试下面的代码: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];            }        }    }}检查它

繁花不似锦

我相信在某些情况下,这会$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}
打开App,查看更多内容
随时随地看视频慕课网APP