计数阵列内部的数组? php
如何专门计算数组内部的数组? 例如:
$array = [ 10, 'hello', [1, 2, 3, ['hi', 7]], [15, 67], 12 ]
输出应为3。
How to specifically count arrays inside of an array?
For example:
$array = [ 10, 'hello', [1, 2, 3, ['hi', 7]], [15, 67], 12 ]
Output should be 3.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以为此使用递归功能。让我给你举个例子:
示例
https://rextester.com/sov87180
解释
功能如何运行如何运行。
[10,'Hello',[1,2,3,['Hi',7]],[15,67],12]
发送到CountiTemsinArray
函数[1,2,3,['hi',7],7]
。请记住,与整个数组一起调用的相同功能还没有死。它只是在等待此
countItemsinArray([1,2,3,['hi',7]])
要完成countitemsinarray(['hi',7])
被调用。请记住,带有完整数组的CountItemsinArray作为参数
和
countitemsinarray([[1,2,3,['hi',7]])现在正在等待countitemsinarray(['hi'',', 7])
要完成countitemsinarray([1,2,3,['hi',7]]))
countitemsinarray([1,2,3,[[''''嗨,7]]])
认识到它无需评估。控制权回到CountItemsinArray($ array)。数组($ array)评估12并确定这也不是数组。因此,它结束了其工作。
然后,回声回应了数组计数为3。
You can use a recursive function for that. Let me give you an example:
Example
https://rextester.com/SOV87180
Explanation
Here's how the function would operate.
[ 10, 'hello', [1, 2, 3, ['hi', 7]], [15, 67], 12 ]
is sent tocountItemsInArray
function[1, 2, 3, ['hi', 7]
.Remember, this same function called with the entire array is not dead. It's just waiting for this
countItemsInArray([1, 2, 3, ['hi', 7]])
to be donecountItemsInArray(['hi', 7])
is called.Remember that countItemsInArray with the full array as the parameter
AND
countItemsInArray([1, 2, 3, ['hi', 7]]) are now waiting forcountItemsInArray(['hi', 7])
to be donecountItemsInArray([1, 2, 3, ['hi', 7]])
countItemsInArray([1, 2, 3, ['hi', 7]])
recognizes that it has nothing more to evaluate. Control is given back to countItemsInArray($array).countItemsInArray($array) evaluates 12 and determines that's not an array either. So, it ends its work.
Then, echo echoes out that array count is 3.
递归迭代您的输入数组,然后在输入数组中的新级别时重新启动TALLY变量。每次遇到一个阵列时,添加一个并重复。从更深层次的层次中传递出级数,当级别完全穿越时,返回顶级的累积计数。
代码:( demo )
Recursively iterate your input array and restart the tally variable upon entering a new level in the array. Every time an array is encountered, add one and recurse. Pass up the tallies from the deeper levels and when the levels are completely traversed, return the top level's cumulative tally.
Code: (Demo)