【问题标题】:multi-dimensional array possibly多维数组可能
【发布时间】:2014-01-08 19:38:24
【问题描述】:

我有两个文件需要打开,我正在使用 php 文件来读取它们

$lines = file('/home/program/prog_conf.txt');
foreach ($lines as $line) {
$rows = preg_split('/\s+/', $line);

接着是:

 $lines = file('/home/domain/public_html/base/file2.cfg');
 foreach ($lines as $line) {
 $rows = preg_split('/=/', $line);

当我使用这两个文件时,我需要从第二个文件中提取信息,我用 = 分隔,但是,我不确定这是最好的做法。我想从数据库中添加数据检查。 db 详细信息在第二个文件中,如下所示:

dbname = databasename
dbuser = databaseuser
dbpass = databasepassword

如果我回显 $rows[2],我会在一行中获得我需要的所有信息,而不是在单独的行中。含义:

databasename databaseuser databasepassword

如何拆分信息以便我可以一一使用条目?

【问题讨论】:

  • parse_ini_file 对第二个文件有效吗?另外,显示echo,你不是忘记输出换行符了吗? ("\n" / PHP_EOL),你怎么看?在 HTML 模式的浏览器中......它当然会在视觉上为您删除换行符,但它们仍然存在(查看源代码)。
  • 旁注:If 您正在使用此方法进行数据库访问,我强烈建议您不要使用此方法,或使用.htaccess 保护它和/或将其置于@987654331 之外@访问。
  • 我打算在程序文件夹中使用,该文件夹远离网络文件夹,但作为计划的 cron。将根据我稍后添加的检查更新数据库或文件的内容。
  • 我还没有对 parse_ini_file 进行研究或阅读。

标签: php arrays file-io multidimensional-array


【解决方案1】:

怎么样:

$lines = file('/home/domain/public_html/base/file2.cfg');
$all_parts = array()
foreach ($lines as $line) {
  //explode pulls apart a string based on the first value, so you could change that 
  //to a '=' if need be
  array_merge($all_parts,explode(' ', $line));
}

这会将文件的所有部分,一次一个,放入一个数组中。这就是我认为你想要的。

如果没有,just explode as needed

【讨论】:

    【解决方案2】:

    也许这种方法有帮助:

    首先我看到你的第二个文件有多行,所以会做这样的事情: 假设每个键都是“db”,我们可以做这样的事情。

    $file = fopen("/home/domain/public_html/base/file2.cfg", "rb");
    $contents = stream_get_contents($handle); // This function return better performance if the file isn't too large.
    fclose($file);
    
    // Assuming this is your return from the file
    $contents = 'dbname = databasename dbuser = databaseuser dbpass = databasepassword';
    
    $rows = preg_split('/db+/', $contents); // Splinting keys "db"
    $result = array();
    foreach($rows as $row){
       $temp = preg_replace("/\s+/", '', $row); // Removing extract white spaces
       $temp = preg_split("/=/", $temp);        // Splinting by "="
       $result[] = $temp[1];                    // Getting the value only
    }
    
    var_dump ($result);
    

    我希望这可以帮助您尝试此代码,可能只需稍作修改即可。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-16
      • 2014-11-07
      • 1970-01-01
      • 1970-01-01
      • 2022-01-15
      • 2013-02-12
      相关资源
      最近更新 更多