Если вы пытаетесь выполнить рекурсивную функцию, делайте рекурсивные вызовы.Это точно не написано для вашего случая, но показывает процесс.
<?php
$folders = array('folder1' => array
('folder2' => array
('folder3' => null,
'folder4' => array
('folder5' => null
)
),
'folder6' => array
('folder7' => null
)
),
'folder8' => array
('folder9' => null,
'folder10' => array
('folder11' => null,
'folder12' => null,
'folder13' => null
)
)
);
function countFolders($folders, $numFolders = 0) {
foreach ($folders as $folderName => $subFolders) {
// increment the number of folders we've encountered
$numFolders++;
// if this folder has subfolders...
// This might be a function call, such as 'hasSubFolders'
// or another check, such as an array key existing, or
// an object property existing or being set to 1 or more
// etc.
if (is_array($subFolders)) {
// count how many additional subfolders there are,
// passing in the current folder count, and updating
// our own copy with the new count
$numFolders = countFolders($subFolders, $numFolders);
}
}
// return the total number of folders
return $numFolders;
}
echo countFolders($folders), "\n";
Будет выводить:
13
В качестве альтернативы, вы можете использовать ссылочную переменную:
function countFolders($folders, &$numFolders = 0) {
foreach ($folders as $folderName => $subFolders) {
$numFolders++;
if (is_array($subFolders)) {
countFolders($subFolders, $numFolders /* passed as a reference */);
}
}
return $numFolders;
}
(обратите внимание на &
в списке параметров функции)