php - 如何避免似乎是有效数组的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) 的解决方案?这就像一种全新的语法,然后生物会在随后的 ';' 上抛出错误 或 {} 个字符。非常混乱,我试图理解。任何帮助将不胜感激,谢谢!
解决方案
如果您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);
}
}
}
}
}
}
?>
推荐阅读
- javascript - 如何根据最高 z-index 获取元素属性
- python - 在返回差异天数的 Dataframe 中减去两个日期
- python - Python pandas 在输出 csv 文件中保留十进制逗号
- android - 直接回复按钮不发送广播意图
- python - Python有时无法将字符串转换为浮点数
- git - 如何处理功能分支差异创建
- typescript - TypeScript 泛型:从函数参数推断键值返回类型的键
- python-3.x - 在python中解析http响应集cookie字符串
- php - PHP警告Wordpress中的非法字符串偏移
- azure - CosmosDB 存储过程未返回所有文档