首页 > 解决方案 > 带循环的函数php

问题描述

在 index.php 中,我有列出文件夹的数组。Function.php 有计算文件夹大小的代码。当我手动键入文件夹名称时,该代码有效。我不知道如何使 function.php 中的代码对 index.php 中的所有文件夹计数。在 index.php 中我做了一个循环foreach ($nameFolders as $index => $value) {echo $nameFolders[$index];},但它在 function.php 中不起作用$disk_used = foldersize ($nameFolders[$index]);

索引.php

$nameFolders = array("nameFolder1", "nameFolder2", "nameFolder3");

foreach ($nameFolders as $index => $value) {
    echo $nameFolders[$index];
}

include 'function.php';

函数.php

$units = explode(' ', 'B KB MB GB');
$disk_used = foldersize($nameFolders[$index]);
$totalSize = format_size($disk_used);

function foldersize($path)
{
    $total_size = 0;
    $files = scandir($path);
    $cleanPath = rtrim($path, '/').'/';
    foreach ($files as $t) {
        if ($t <> "." && $t <> "..") {
            $currentFile = $cleanPath.$t;
            if (is_dir($currentFile)) {
                $size = foldersize($currentFile);
                $total_size += $size;
            } else {
                $size = filesize($currentFile);
                $total_size += $size;
            }
        }
    }

    return $total_size;
}

function format_size($size)
{
    global $units;
    $mod = 1024;
    for ($i = 0; $size > $mod; $i++) {
        $size /= $mod;
    }
    $endIndex = strpos($size, ".") + 3;

    return substr($size, 0, $endIndex).' '.$units[$i];
}

标签: php

解决方案


include从订单开始,您的代码有几处错误。如果在循环之后包含(并因此声明)函数,则不能在循环内使用它们;我了解到您正在尝试按大小打印所有文件夹。

索引.php

<?php

include_once('function.php'); // this needs to happen before.

$name_folders = array('nameFolder1', 'nameFolder2', 'nameFolder3');

// no need for key => value here if you don't use that
foreach ($name_folders as $folder) {

    $disk_used = folder_size($folder);
    $totalSize = format_size($disk_used);

    echo "$folder: $totalSize\n";
}

函数.php

<?php

$units = explode(' ', 'B KB MB GB');

function folder_size($path)
{
    $total_size = 0;
    $files = scandir($path);
    $cleanPath = rtrim($path, '/').'/';
    foreach ($files as $t) {
        if ($t <> "." && $t <> "..") {
            $currentFile = $cleanPath.$t;
            if (is_dir($currentFile)) {
                $size = folder_size($currentFile);
                $total_size += $size;
            } else {
                $size = filesize($currentFile);
                $total_size += $size;
            }
        }
    }

    return $total_size;
}

function format_size($size)
{
    global $units;
    $mod = 1024;
    for ($i = 0; $size > $mod; $i++) {
        $size /= $mod;
    }
    $endIndex = strpos($size, ".") + 3;

    return substr($size, 0, $endIndex).' '.$units[$i];
}

请注意,这种“include function.php”风格的 PHP 是我们在 1999 年所做的,它并不是真正的现代实践。那里的使用也是如此global。尝试坚持 ONE 命名约定:将 camelCase 与 snake_case 混合使用。


推荐阅读