【问题标题】:count(): Parameter must be an array or an object that im plements Countable error based on the array sizecount():参数必须是数组或对象,根据数组大小实现Countable error
【发布时间】:2019-11-08 19:55:23
【问题描述】:

只有在返回的数组太长时才会在下面的代码中产生这个错误。使用短数组(我不知道具体有多少)不会发生。

$phone_numbers = array();
if(!empty($_POST['phone_numbers']))
    $phone_numbers = json_decode($_POST['phone_numbers']);
    $phone_numbers_var = str_repeat('?,', count(json_decode($_POST['phone_numbers'])) - 1) . '?'; // <-- error line

count()参数有限制吗?

【问题讨论】:

标签: php arrays json count


【解决方案1】:

首先检查你 $_POST['phone_numbers'] 得到了什么

记住:

var_dump(count(null));var_dump(count(false));

将输出:

Warning: count(): Parameter must be an array or an object that implements Countable in

我认为 PHP 7.2 版的计数有点奇怪......但你可以尝试这样的事情:

https://wiki.php.net/rfc/counting_non_countables

编辑:

仅供评论:

$POST['phone_numbers'] = [165567, 545675, 655666];

如果你尝试这样做:

json_decode($POST['phone_numbers']);

将返回:

WARNING json_decode() expects parameter 1 to be string, array given on line number 4

还有数......你知道..就这样做:

count($POST['phone_numbers']);

【讨论】:

  • $phone_numbers 返回 [165567, 545675, 655666, ..., n]
  • @afazolo 所以在他身上加上count 而不是在POST 的解码上
  • 由于返回数据的完整性,出现此问题。谢谢你的帮助。
【解决方案2】:

很有趣,但似乎如果数组中有一些以 0 开头的数字,则会发生错误。当我删除初始 0 时就可以了。

 $phone_numbers = [011364346387, 33334444, ..., n] //error
 $phone_numbers = [11364346387, 33334444, ..., n] //is ok!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-26
    • 2019-05-10
    • 2021-05-30
    • 2018-06-28
    • 2018-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多