PHP count() 在非空数组上返回 NULL

标签 php arrays php-7.1

我将一大堆数据填充到一个数组中(通过从内存缓存中提取或查询数据库)。我想计算这个数组中有多少行,以确保它大于 0。当我使用 count() 时,即使数组已充满数据,它也不会返回任何内容。

为了进行故障排除,我尝试了以下代码:

$item_count=count($item_data);
print_r($item_data);
die($item_count);

这会打印出一个巨大的数组,我可以看到它有 146 个元素。但 $item_count 为 NULL。知道可能出什么问题吗?谢谢!

根据评论中的要求,以下是我要计算的数组的示例:

Array
(
    [0] => Array
        (
            [calories] => 190
            [healthy_option] => 0
            [name] => Chicken McNuggets
            [url_name] => chicken-mcnuggets
            [category_name] => Chicken Nuggets and Strips
            [category_url_name] => chicken-nuggets-strips
            [category_id] => 85
        )

    [1] => Array
        (
            [calories] => 380
            [healthy_option] => 0
            [name] => Chicken Selects Premium Breast Strips - 3 piece
            [url_name] => chicken-selects-premium-breast-strips-3-piece
            [category_name] => Chicken Nuggets and Strips
            [category_url_name] => chicken-nuggets-strips
            [category_id] => 85
        )

)

最佳答案

die()函数的行为类似于 exit() 。 这意味着整数参数被视为“状态”。

来自文档:

If status is an integer, that value will be used as the exit status and not printed. Exit statuses should be in the range 0 to 254, the exit status 255 is reserved by PHP and shall not be used. The status 0 is used to terminate the program successfully.

如果你想打印一个值,我建议你使用其他东西,比如 echo、print_r 等。

如果不使用 die(),你是否也会遇到同样的问题?

关于PHP count() 在非空数组上返回 NULL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44459811/

相关文章:

java - 逗号导致不必要的字符串分割

arrays - 如何将字符串转换为 BASH 数组?

PHP7.1 使用 memcached 作为保存处理程序, session 启动缓慢

javascript - 如何使用 JavaScript 在 HTML 数据表中可视化 MySQL 表中超过 1000 行的数据?

php - 当项目在指定列中具有相同值时合并 SQL 数据库值

php - 我是否正确使用了 __DIR__?

php - 迁移网站 - 在迁移过程中保持数据库同步

arrays - VBA循环填充数组

nginx - 如何在使用 nginx 作为 Web 服务器的 Amazon Linux AMI 2018.03 上运行的 EC2 上安装 PHP 7.1?

php - 开发者工具出现语法错误