将数组传递给另一个函数

问题描述 投票:0回答:2

嘿家伙我的实验有一些问题基本上我试图读取一个文件,然后将其放入一个数组,并希望在其他功能中使用该数组。

   $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>';

我没有得到任何错误,但我也没有得到结果,我知道信息位于正确的位置,在文件中我认为这是我的第一个功能,即没有完成工作,即返回/通过数组..

任何帮助都会很棒!

php arrays
2个回答
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>';
?>

0
投票

您没有存储函数处理程序的结果。或者调用函数带。需要一些东西

$result = handler($weekly);
$totalBand = band($result);
echo '<p>Total band = ' . $totalBand . 'bytes</p>';

如果需要,可以链接或做一个单行,但它看起来很难看。

可能想要在Scope上读取,因为看起来你正在尝试从全局范围访问本地函数变量。函数完成后,您无法再访问函数内部的变量,除非它们是全局声明的。

© www.soinside.com 2019 - 2024. All rights reserved.