How to specifically count arrays inside of an array?
$array = [ 10, 'hello', [1, 2, 3, ['hi', 7]], [15, 67], 12 ]
输出应该是3.
How to specifically count arrays inside of an array?
$array = [ 10, 'hello', [1, 2, 3, ['hi', 7]], [15, 67], 12 ]
输出应该是3.
可以使用递归函数来实现这一点.我举个例子:
<?php
$array = [ 10, 'hello', [1, 2, 3, ['hi', 7]], [15, 67], 12 ];
$arrayCount = 0; # this variable will hold count of all arrays found
# Call a recursive function that starts with taking $array as an input
# Recursive function will call itself from within the function
countItemsInArray($array);
function countItemsInArray($subArray) {
# access $arrayCount that is declared outside this function
global $arrayCount;
# loop through the array. Skip if the item is NOT an array
# if it is an array, increase counter by 1
# then, call this same function by passing the found array
# that process will continue no matter how many arrays are nested within arrays
foreach ($subArray as $x) {
if ( ! is_array($x) ) continue;
$arrayCount++;
countItemsInArray($x);
}
}
echo "Found $arrayCount arrays\n";
https://rextester.com/SOV87180
下面是函数的运行方式.
[ 10, 'hello', [1, 2, 3, ['hi', 7]], [15, 67], 12 ]
被发送到countItemsInArray
函数[1, 2, 3, ['hi', 7]
.记住,用整个数组调用的同一个函数不是死函数.它只是在等待这countItemsInArray([1, 2, 3, ['hi', 7]])
件事的完成
countItemsInArray(['hi', 7])
.请记住,参数为AND
countItemsInArray([1,2,3,['hi',7]])的countItemsInArray(完整数组)现在正在等待countItemsInArray(['hi', 7])
的完成
countItemsInArray([1, 2, 3, ['hi', 7]])
countItemsInArray([1, 2, 3, ['hi', 7]])
认识到它没有什么可判断的了.控件返回给countItemsInArray($array).
countItemsInArray($array)计算12并确定它也不是array.所以,它结束了它的工作.
然后,echo回声显示数组计数为3.