【问题标题】:PHP Warning: count(): Parameter must be an array or an object that implements Countable?PHP 警告:count():参数必须是数组还是实现 Countable 的对象?
【发布时间】:2019-10-18 15:48:00
【问题描述】:

在我的网站上,我允许人们上传图片库。当他们点击图片时,底部会出现 下一个上一个 按钮,因此他们可以轻松地在图片中来回滚动。

我在位于 /opt/cpanel/ea-php72/root/usr/var/log/php-fpm/ 的日志中收到以下错误

NOTICE: PHP message: PHP Warning:  count(): Parameter must be an array or an object that implements Countable in . . . on line 12

它在我的代码中谈论以下行:

$max = count($photos);

以下是该行附带的其他代码:

$photos = get_field('gallery');
$max = count($photos);    <------- error line here -------->
$current = (isset($_GET['image'])) ? intval($_GET['image']) : false;
if ($current !== false) {
    if ($current > $max) $current = $max;
    if ($current < 1) $current = 1;
}

$next = (($current + 1) < $max) ? ($current + 1) : $max;
$prev = (($current - 1) > 1) ? ($current - 1) : 1;
?>

基本上这段代码使用 get_field('gallery') 来获取图库中的照片总数,并将数量分配给变量 ma​​x

其余的代码是下一个上一个按钮的工作原理。

我不知道出了什么问题。有人可以帮忙吗?

【问题讨论】:

  • get_field() 是做什么的?
  • 嗯,让我看看。它是我正在使用的 Wordpress 主题文件的一部分,所以我不太清楚。让我了解一下
  • 请做一些基本的调试。在 count($photos); 之前添加 var_dump($photos); 以查看变量实际包含的内容。它显然不是任何可数类型。此外,get_field() 最常与插件“高级自定义字段”一起使用。
  • 是的,我现在看到了。我已经安装了 ACF。谢谢。

标签: php arrays wordpress


【解决方案1】:

一般来说,解决方法很简单:

第一次调试 var_dump() 什么 $photos 返回。然后你就会知道问题出在哪里了。

count() 接受数组,如果您有 falsenull 或其他任何内容,则会出现错误。

只要做这样的事情:

$photos = get_field('gallery');
if(!is_array($photos) || empty($photos)) $photos = array(); // FIX ERROR!!!
$max = count($photos);    <------- error line here -------->
$current = (isset($_GET['image']) && !empty($_GET['image']) && is_numeric($_GET['image'])) ? intval($_GET['image']) : 0;
if ($current > 0) {
    if ($current > $max) $current = $max;
    if ($current < 1) $current = 1;
}

$next = (($current + 1) < $max) ? ($current + 1) : $max;
$prev = (($current - 1) > 1) ? ($current - 1) : 1;
?>

$max = count($photos); 之前使用if(!is_array($photos) || empty($photos)) $photos = array();,您可以解决您的问题,并且任何不是数组或空(0、NULL、FALSE、'')的内容都将得到修复,您将在计数$max 结果0因为数组是空的。


重要!!!

你不应该这样工作。你需要知道你在变量中接收和期望什么信息。代码必须保持干净,纠正此类错误是一种不好的做法。如果您收到一个数组,则该数组是预期的,并且您必须在进行任何计算之前进行检查。


更新:

你也有错误

$current = (isset($_GET['image'])) ? intval($_GET['image']) : false;
if ($current !== false)

我把它改成这样:

$current = (isset($_GET['image']) && !empty($_GET['image']) && is_numeric($_GET['image'])) ? intval($_GET['image']) : 0;
if ($current > 0)

原因是您在下面进行了计算,并且您不希望 (false + 1) 是好东西。 false 可以翻译为 0 但在您的情况下,您也可能会出错。对于这种情况,我将false 替换为0,添加empty()is_numeric() 检查,您没有错误。

【讨论】:

  • 我会用这个看看效果如何。谢谢!!
猜你喜欢
  • 2019-08-15
  • 2018-12-19
  • 1970-01-01
  • 2018-09-10
  • 2019-06-20
  • 2020-01-18
  • 2019-01-06
  • 2020-01-27
  • 2020-01-26
相关资源
最近更新 更多