问题
I'm getting a php count() error, 'Warning: count(): Parameter must be an array or an object that implements Countable' on what is clearly an array. The code still works, but I'd like to know how to recode to avoid the warning messages.
First, I have a multidimensional array (print_f dump):
$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
)
)
)
And I'm matching up Wordpress terms to images:
<?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);
}
}
}
}
}
} ?>
The error occurs in the first for() loop while counting the nested array. I've actually been using this same code for months now, with two instances on two separate documents. I'm only getting this error on one of the documents. I've been pulling my hair out trying to understand why the array not typing as an array.
I've seen some solutions discussed that use the array variable && count($array) in a conditional?? It's like an all new syntax that then beings to throw errors on subsequent ';' or {} characters. Very confusing, I'm trying to get an understanding. Any help would be much appreciated, Thanks!
回答1:
You can use is_countable()
if you are using PHP 7.3
otherwise you can use is_array()
.
For PHP 7.3 or above:
<?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);
}
}
}
}
}
}
?>
For below 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);
}
}
}
}
}
}
?>
回答2:
You can use the function is_countable if you are unsure whether you can use count
on the variable in question.
来源:https://stackoverflow.com/questions/57053360/how-to-avoid-php-countable-errors-on-what-appear-to-be-valid-arrays