Php 我想写一个函数,打开一系列文件并将一些数据复制到数组中

Php 我想写一个函数,打开一系列文件并将一些数据复制到数组中,php,Php,我想写一个函数,因为很多代码都是重复的,但是我在将文件名和模式作为参数传递给函数时遇到了麻烦 name = array(); dob = array(); address = array(); data = array(); #get name data $handle = fopen('data/name.txt', 'r'); while (!feof($handle)) {

我想写一个函数,因为很多代码都是重复的,但是我在将文件名和模式作为参数传递给函数时遇到了麻烦

        name = array();
        dob = array();
        address = array();
        data = array();

        #get name data
        $handle = fopen('data/name.txt', 'r');
        while (!feof($handle)) {
            $data = explode(':',fgets($handle, 1024));
            $name[] = $data[1];
        }
        fclose($handle);

        #get dob data
        $handle = fopen('data/dob.txt', 'r');
        while (!feof($handle)) {
            $data = explode(':',fgets($handle, 1024));
            $dob[] = $data[1];
        }
        fclose($handle);

        #get address data
        $handle = fopen('data/address.txt', 'r');
        while (!feof($handle)) {
            $data = explode(':',fgets($handle, 1024));
            $address[] = $data[1];
        }
        fclose($handle);
这是我写的函数

        function get_data($file, $mode, $array) {
        $handle = fopen("'" . $file . "'", "'" . $mode . "'");
        while (!feof($handle)) {
        $data = explode(':',fgets($handle, 1024));
        $array[] = $data[0];
      }
因此,我希望能够调用每个文件上的函数,例如

      get_data ('data/name.txt' , 'r', $name);

您的函数几乎正确:)只有两个错误

  • 您没有在函数中调用
    fclose()
  • 您尝试过两次将字符串括起来,一次就足够了

    function get_data($file, $mode, $array) {
       $handle = fopen("'" . $file . "'", "'" . $mode . "'");
       #               /\ these       /\ and these are unnecessary
    
       while (!feof($handle)) {
       $data = explode(':',fgets($handle, 1024));
       $array[] = $data[0];
    }
    
    只需调用
    fopen($file$mode)
    就可以了:)

  • 如果要在函数之外使用
    $array
    变量,请记住返回它。如果添加
    返回$array在功能结束时,您将能够:

    $result = get_data('file.txt', 'r');
    
PS:PHP中已经有一个类似的函数,也许您可以使用它?:)