上一篇
🔥 最新动态(2025年7月)
PHP 8.4 即将引入新的数组统计函数 array_count_distinct()
,可快速计算数组中唯一值的数量,预计年底发布!现在让我们先掌握现有核心技能~
无论是电商平台的商品列表 🛒、社交媒体的用户数据 👥,还是游戏中的道具背包 �,数组统计都无处不在,准确获取数组信息能帮助我们:
count()
函数(最常用)$fruits = ['🍎', '🍌', '🥭']; echo count($fruits); // 输出:3
特点:
COUNT_RECURSIVE
) sizeof()
函数echo sizeof($fruits); // 输出:3
注意:sizeof()
是 count()
的别名,功能完全相同,但建议统一使用 count()
if (empty($array)) { /* 数组为空时的操作 */ } // 或 if (count($array) === 0) { /* 更明确的判断 */ }
$prices = [99, 149, 79, 199]; echo max($prices); // 199(最大值) echo min($prices); // 79(最小值)
echo array_sum($prices); // 526(总和) echo array_sum($prices) / count($prices); // 131.5(手动计算平均值)
$colors = ['red', 'blue', 'red', 'green']; print_r(array_count_values($colors)); /* 输出: Array ( [red] => 2 [blue] => 1 [green] => 1 ) */
$uniqueColors = array_unique($colors); print_r($uniqueColors); /* 输出: Array ( [0] => red [1] => blue [3] => green ) */
$students = [ ['name' => '小明', 'score' => 85], ['name' => '小红', 'score' => 92], ['name' => '小刚', 'score' => 78] ]; // 提取所有分数 $scores = array_column($students, 'score'); echo "平均分:" . array_sum($scores)/count($scores);
count()
而非 sizeof()
// 统计关联数组元素 $user = ['name' => 'Leo', 'age' => 28, 'vip' => true]; echo count($user); // 3(同样适用)
Q:count() 对字符串返回什么?
A:返回1,因为PHP会把字符串视为单元素数组
Q:如何统计数组的维度?
A:可通过递归函数实现,暂无内置方法
Q:统计大量数据时内存不足怎么办?
A:考虑分块处理或使用 SplFixedArray
掌握这些数组统计技巧,你就能像数据分析师一样游刃有余地处理PHP数组啦!🚀 下次遇到复杂统计需求时,记得PHP已经为你准备了丰富的工具~
本文由 西门冠宇 于2025-07-30发表在【云服务器提供商】,文中图片由(西门冠宇)上传,本平台仅提供信息存储服务;作者观点、意见不代表本站立场,如有侵权,请联系我们删除;若有图片侵权,请您准备原始证明材料和公证书后联系我方删除!
本文链接:https://vps.7tqx.com/wenda/483427.html
发表评论