嘿伙计们在我的实验中遇到一些问题基本上我正在尝试读取一个文件,然后把它放到一个数组中,并希望在其他函数中使用该数组。
$totalBand = 0;
$weekly = fopen('filepath', 'r'); //opening my file
handler($weekly); //Calling my function
function handler ($weekly) {
$dataFile = array();
while (!feof($weekly)) {
$line=fgets($weekly);
//add to array
$dataFile[]=$line; //pitting file into an array
}
fclose($weekly); //closing file
return $dataFile; //returning the array
}
function band ($datafile) {
//function for counting data from each line of the array from 1st function
$totalBand = 0;
foreach ($datafile as $lines) {
$pieces = explode(" ", $lines); //exploding file
if ($totalBand > 0) {
$totalBand = $totalBand + $pieces [7];
//extracting information from the 7th position in every line
}
}
return $totalBand; // total value from the file
}
echo '<p>Total band = ' . $totalBand . 'bytes</p>';
我没有得到任何错误,但我也没有得到结果,我知道信息位于正确的位置,在文件中我认为这是我的第一个功能,即没有完成工作,即返回/传递数组..
任何帮助都会很棒!
答案 0 :(得分:0)
您没有存储函数处理程序的结果。或者调用函数 band 。
需要一些东西$result = handler($weekly);
$totalBand = band($result);
echo '<p>Total band = ' . $totalBand . 'bytes</p>';
如果需要,可以链接或做一个单行,但它看起来很难看。
可能想要在Scope上进行读取,因为看起来你正试图从全局范围访问本地函数变量。函数完成后,您不能再访问函数内部的变量,除非它们是全局声明的。
答案 1 :(得分:0)
<?php
$totalBand = 0;
$weekly = fopen('filepath', 'r'); //opening my file
//Add this
$datafile=handler($weekly); //Calling my function
//Add This
$totalBand=band($datafile); //Calculating datafile
function handler ($weekly) {
$dataFile = array();
while (!feof($weekly)) {
$line=fgets($weekly);
//add to array
$dataFile[]=$line; //pitting file into an array
}
fclose($weekly); //closing file
return $dataFile; //returning the array
}
function band ($datafile) {
//function for counting data from each line of the array from 1st function
$totalBand = 0;
foreach ($datafile as $lines) {
$pieces = explode(" ", $lines); //exploding file
if ($totalBand > 0) {
$totalBand = $totalBand + $pieces [7];
//extracting information from the 7th position in every line
}
}
return $totalBand; // total value from the file
}
echo '<p>Total band = ' . $totalBand . 'bytes</p>';
?>