猿问

我该如何修复此 PHP 错误 - 参数必须是实现 Countable 的数组或对象?

我在这条线上遇到错误,不知道如何纠正它,有什么帮助吗?

我的 php 能力为零甚至没有,只想修复我所做的一些工作中的错误。该修复程序还会向后兼容 PHP7 到 PHP5 吗?

for($k=0;$k<count($_matchup['franchise'][$m]['player']);$k++){


猛跑小猪
浏览 151回答 2
2回答

拉莫斯之舞

在 PHP 7.2 中,如果您对不可数的变量调用 count(),PHP 会显示有关它的警告。一个常见的解决方法是在调用 count() 之前检查给定变量是否是“可数”。“可数”变量可以是数组,也可以是实现 \Countable 接口的类的对象。因为可能有很多样板代码,所以 PHP 7.3 现在有一个新的 is_countable() 函数,如果传递的变量是……嗯……可数,则该函数返回 true。https://php.watch/versions/7.3#new-is_countable-function我会做这样的事情:if(isset($_matchup['franchise'][$m]['player']) && is_countable($_matchup['franchise'][$m]['player']) {&nbsp; &nbsp; for($k=0;$k<count($_matchup['franchise'][$m]['player']);$k++){&nbsp; &nbsp; &nbsp; &nbsp; ...&nbsp; &nbsp; }}如果你的版本低于 7.3,请将这个 polyfill 放入你的代码中:if (!function_exists('is_countable')) {&nbsp; &nbsp; function is_countable($var) {&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; return is_array($var)&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; || $var instanceof Countable&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; || $var instanceof ResourceBundle&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; || $var instanceof SimpleXmlElement;&nbsp;&nbsp; &nbsp; }}

慕哥6287543

请确保它$_matchup['franchise'][$m]['player']实际上是一个可以计数的变量。正如错误消息所示。比如数组这行代码应该兼容 PHP5 和 PHP7
随时随地看视频慕课网APP
我要回答