首页 > 解决方案 > 如何避免似乎是有效数组的php可数错误

问题描述

我收到一个 php count() 错误,“警告:count():参数必须是一个数组或实现 Countable 的对象”,显然是一个数组。该代码仍然有效,但我想知道如何重新编码以避免警告消息。

首先,我有一个多维数组(print_f 转储):

$icons Array
(
[0] => Array
    (
        [image] => 12811
        [label] => Chemical
        [categories] => Array
            (
                [0] => 209
            )

    )

[1] => Array
    (
        [image] => 12812
        [label] => Cut
        [categories] => Array
            (
                [0] => 236
            )

    )

[2] => Array
    (
        [image] => 12813
        [label] => Flame
        [categories] => Array
            (
                [0] => 256
                [1] => 252
            )

    )
)

我正在将 Wordpress 术语与图像匹配:

<?php 
$terms = wp_get_post_terms( get_the_ID(), 'product_categories', array("fields" => "ids"));
if($icons) {

foreach($icons as $row) {
    for($i=0; $i<count($row['categories']); $i++) {
        for($j=0; $j<count($terms); $j++) {
            if($row['categories'][$i]==$terms[$j]) {
                       array_push($icon_img_ary,$row['image']);
                                $icon_img_ary_unq=wg_unique_array($icon_img_ary);
                       }
                }
          }
      }
}
} ?>

计算嵌套数组时,错误发生在第一个 for() 循环中。实际上,我几个月来一直在使用相同的代码,在两个单独的文档中有两个实例。我只在其中一份文件上收到此错误。我一直在努力理解为什么数组没有作为数组输入。

我已经看到了一些在条件中使用数组变量 && count($array) 的解决方案?这就像一种全新的语法,然后生物会在随后的 ';' 上抛出错误 或 {} 个字符。非常混乱,我试图理解。任何帮助将不胜感激,谢谢!

标签: phpwordpresswordpress-theming

解决方案


如果您is_countable()使用的是 PHP ,则可以使用,7.3否则您可以使用is_array().

对于 PHP 7.3 或更高版本:

<?php 
$terms = wp_get_post_terms( get_the_ID(), 'product_categories', array("fields" => "ids"));
if($icons) {

    foreach($icons as $row) {
        if ( is_countable( $row['categories'] ) ) {
            for($i=0; $i<count($row['categories']); $i++) {
                for($j=0; $j<count($terms); $j++) {
                    if($row['categories'][$i]==$terms[$j]) {
                        array_push($icon_img_ary,$row['image']);
                        $icon_img_ary_unq=wg_unique_array($icon_img_ary);
                    }
                }
            }
        }
    }
}
?>

对于 PHP 7.3 以下:

<?php 
$terms = wp_get_post_terms( get_the_ID(), 'product_categories', array("fields" => "ids"));
if($icons) {

    foreach($icons as $row) {
        if ( is_array( $row['categories'] ) ) {
            for($i=0; $i<count($row['categories']); $i++) {
                for($j=0; $j<count($terms); $j++) {
                    if($row['categories'][$i]==$terms[$j]) {
                        array_push($icon_img_ary,$row['image']);
                        $icon_img_ary_unq=wg_unique_array($icon_img_ary);
                    }
                }
            }
        }
    }
}
?>

推荐阅读