php - 带循环的函数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];
}
解决方案
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 混合使用。
推荐阅读
- java - 而不是 Value(Long) Null 在 JSP 中传递,因此正确的值不会显示在 JSP 页面中
- python - Pyranges中重叠和相交方法的区别
- google-colaboratory - 不支持符号链接 (ln) 操作 Colab
- javascript - 当我在 vue 方法中使用 setInterval 时数据变量未定义
- java - 根据条件合并两个列表并使用 java 8 将结果推送到地图
- protractor - 错误:在 config.yml 文件上 ng e2e -- --protractor-config=./e2e/protractor-ci.conf.js 时生成 chromedriver
- php - 集成 CCAVENUE 支付网关时面临的问题
- c# - “违反主键约束'...'。无法在对象中插入重复键
- google-sheets - 如何使用带有公式的新行并被视为空行
- c++ - 访问类的功能不起作用