从文本文件中读取行并将其存储在多维数组 php 中


Read lines from a text file and store it in a multi-dimensional array php

G'day,

所以我一直在尝试从.txt文件中读取一些行并将其存储为多维数组。

文本文件如下所示 -

 John, BOL12345
 Mary2, BOL77777
 Anna, BOL54321

这是我的代码——

 <?php
 $fileUsername = array();
 $filePassword = array();
 $myFile = "../../data/manager.txt";
 $openFile = fopen($myFile, "r");
  if (file_exists($myFile))
  {
     while (!feof($openFile))
     { 
       $login = fgets($openFile);
       $fileUsername = explode(", ", $login);
       $filePassword = explode(" ", $login);
       echo $fileUsername[0];
       echo $filePassword[1];
       echo "<br>"; 
     }
      fclose($openFile);
  }
  else
  {
    echo "File doesn't exists!";
  } 
  ?>

我想做的是读取文件并存储这样的值 -

$fileUsername = [John,Mary2,Anna];
$filePassword = [BOL12345,BOL77777,BOL54321];

任何帮助都值得赞赏:)

更好地使用file函数

if (file_exists($myFile))
{
     $fileContent = file($myFile);
     foreach($fileContent as $line_num => $line) {
     { 
       $data = explode(", ", $line);
       $fileUsername[] = trim($data[0]);
       $filePassword[] = trim($data[1]);
     }
}

您是否考虑过改用序列化?