如何專門計算陣列內的陣列? 例如:
$array = [ 10, 'hello', [1, 2, 3, ['hi', 7]], [15, 67], 12 ]
輸出應該是 3。
uj5u.com熱心網友回復:
您可以為此使用遞回函式。讓我給你舉個例子:
<?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函式- 此函式查看陣列中的每個專案
- 10 被審查。它不是陣列,所以函式轉到下一項
- '你好' 被審查。它不是陣列,所以函式轉到下一項
- [1, 2, 3, ['hi', 7]] 被評估。它是一個陣列,因此 arrayCount 增加到 1 并呼叫相同的函式,但現在函式的輸入是
[1, 2, 3, ['hi', 7]。
請記住,用整個陣列呼叫的同一個函式并沒有死。它只是在等待countItemsInArray([1, 2, 3, ['hi', 7]])完成
- 1 被評估。它不是一個陣列,所以下一個專案被評估
- 2 被評估...
- 3被評估...
- ['hi', 7] 被評估。它是一個陣列。因此,陣列計數增加到 2
countItemsInArray(['hi', 7])叫做。
請記住,以完整陣列作為引數的ANDcountItemsInArray([1, 2, 3, ['hi', 7]]) 現在正在等待countItemsInArray(['hi', 7])完成
- 你好被評估。那不是陣列,所以函式測驗下一項
- 7 被評估。那也不是一個陣列。因此,該功能完成,將控制權交還給
countItemsInArray([1, 2, 3, ['hi', 7]])
countItemsInArray([1, 2, 3, ['hi', 7]])認識到它沒有什么要評估的了。控制權交還給 countItemsInArray($array)。
- [15, 67] 進行了評估。它是一個陣列,因此陣列計數增加到 3
- countItemsInArray([15, 67]) 被呼叫,它計算 15 和 16 并確定它們都不是陣列,因此它將控制權交還給 countItemsInArray($array)
countItemsInArray($array) 計算 12 并確定它也不是一個陣列。所以,它結束了它的作業。
然后, echo 回顯出陣列計數為 3。
uj5u.com熱心網友回復:
遞回迭代您的輸入陣列并在陣列中輸入新級別時重新啟動計數變數。每次遇到陣列時,加一個并遞回。從更深的級別傳遞計數,當級別完全遍歷時,回傳頂層的累積計數。
代碼:(演示)
$array = [10, [[[]],[]], 'hello', [1, 2, 3, ['hi', 7]], [15, 67], 12];
function array_tally_recursive(array $array): int {
$tally = 0;
foreach ($array as $item) {
if (is_array($item)) {
$tally = 1 array_tally_recursive($item);
}
}
return $tally;
}
echo array_tally_recursive($array);
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/463722.html
