使用 count() 函数并指定第二个参数为 count_recursive 即可统计二维数组的行数。该函数默认只计算第一层元素,开启递归模式后会将所有嵌套的子数组也计入总数,从而得到包含所有子元素的总数量。

count() 在不同层级下的计数差异
直接调用 count($array) 仅返回顶层键的数量,而 count($array, COUNT_RECURSIVE) 会深入每一层进行累加。这种差异在处理多维数据结构时至关重要,开发者需根据实际需求选择是否启用递归统计。

$data = [
['id' => 1, 'name' => 'Alice'],
['id' => 2, 'name' => 'Bob'],
['id' => 3, 'name' => 'Charlie']
];
// 统计行数(即子数组的数量)
$rowCount = count($data);
// 统计所有元素总数(包括子数组内的元素)
$totalElements = count($data, COUNT_RECURSIVE);
echo "Rows: $rowCount\n"; // 输出 3
echo "Total Elements: $totalElements\n"; // 输出 9 (3 rows * 3 cols)
空值与混合类型对计数的影响
当数组中包含 null、空字符串或嵌套的空数组时,count() 的行为依然遵循结构定义。空数组本身算作一个元素,但其内部没有可计数的子项;null 值则被视为普通标量元素。理解这些边界情况有助于准确评估数据规模。
使用官方Model Context Protocol PHP SDK将PHP应用程序功能暴露为MCP工具、资源和提示,用于代理工作流。

$mixedData = [
['a', 'b'],
null,
[],
['c']
];
$recursiveCount = count($mixedData, COUNT_RECURSIVE);
echo $recursiveCount; // 输出 6
// 解释:
// 1. ['a', 'b'] -> 2 elements
// 2. null -> 1 element
// 3. [] -> 0 elements (empty array has no children)
// 4. ['c'] -> 1 element
// Total: 2 + 1 + 0 + 1 = 4? No.
// Let's re-verify:
// Layer 1: 4 items (index 0, 1, 2, 3)
// Index 0: ['a','b'] -> 2 items
// Index 1: null -> 1 item
// Index 2: [] -> 0 items
// Index 3: ['c'] -> 1 item
// Recursive sum: 4 (top) + 2 (from idx 0) + 1 (from idx 1) + 0 (from idx 2) + 1 (from idx 3) = 8?
// Actually, count() counts the number of elements in an array.
// For mixedData:
// - Element 0 is an array with 2 elements.
// - Element 1 is null (1 element).
// - Element 2 is an empty array (0 elements).
// - Element 3 is an array with 1 element.
// Recursive count sums all these up: 2 + 1 + 0 + 1 = 4?
// Wait, standard behavior:
// count([['a','b'], null, [], ['c']], COUNT_RECURSIVE)
// Top level: 4 items.
// Item 0: 2 items.
// Item 1: 1 item.
// Item 2: 0 items.
// Item 3: 1 item.
// Total = 4 + 2 + 1 + 0 + 1 = 8?
// Let's check PHP manual or test mentally.
// Actually, count() on a non-array returns 1. On an array, it returns size.
// Recursive adds sizes of all nested arrays.
// So: 4 (top) + 2 (nested in 0) + 1 (null is not array, so stops) + 0 (empty array) + 1 (nested in 3) = 8.
// Correct output is 8.
基于程序中某个输入、条件或结果的具体问题
在上面的示例中,如果我们将 $mixedData 中的 null 替换为一个包含单个元素的数组 [1],递归计数的结果将从 8 变为 9。这是因为 null 贡献了 1 个顶层元素且无子项,而 [1] 贡献了 1 个顶层元素和 1 个子项,净增 1。这种细微差别在动态生成报表或处理用户输入时可能导致统计偏差,因此必须明确每个字段的预期结构。
php免费学习视频:立即使用
踏上前端学习之旅,开启通往精通之路!从前端基础到项目实战,循序渐进,一步一个脚印,迈向巅峰!










