我将一大堆数据填充到一个数组中(通过从内存缓存中提取或查询数据库)。我想计算这个数组中有多少行,以确保它大于 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/