变量可以是要打开的文件名的一部分


Can a variable be a part of a filename that is to be opened?

在PHP中有什么方法可以根据文件名的变量打开文件吗?基本上我想要的是这个:

$file = file('data.txt');
$needle = array("one", "two", "three");
$haystack = array("one", "three");
foreach($needle as $value){
  $pos = strpos($haystack, $value);
if($pos !== false){
  $filename = "$value.txt";
  file_put_contents($filename, $file);
}

$needle的值是.txt文件的名称。它一直工作到file_put_contents。$filename是无效的,我已经四处寻找解决方案并尝试了我能想到的一切。我想加载数组值,说"一",.txt扩展名作为文件名,具体取决于是否在大海捞针中找到该值。有没有办法在不为每个文件名执行 if 语句的情况下执行此操作?如果可能的话,我宁愿用循环来处理它。

已编辑以交换参数。

编辑,新代码:

$data = file_get_contents('data.txt');
$needle = array("one", "two", "three");
$haystack = array("one", "three");
$files = array_intersect($needle, $haystack);
foreach ($files as $value) {
  $newfilename = "$value.txt";
  var_dump($newfilename);
  file_put_contents($newfilename, $data);
}

你混淆了 file_put_contents() 的参数:

int file_put_contents ( 字符串 $filename , 混合 $data [, int $flags = 0 [, 资源 $context ]] )

所以你需要交换它们:

file_put_contents($filename, $file);

第二件事是,你正在一个数组上做一个strpos(),但这个函数(顾名思义)是字符串的 - 你想要的是in_array():

foreach ($needle as $value) {
    if (in_array($value, $haystack) {
        $filename = "$value.txt";
        file_put_contents($filename, $file);
    }
} 

您甚至可以通过使用 array_intersect() 来进一步增强它 - 它为您提供了$haystack中$needle的所有值的数组。我认为这就是您要求避免if语句的原因:

$files = array_intersect($needle, $haystack);
foreach ($files as $value) {
    $filename = "$value.txt";
    file_put_contents($filename, $file);
}

file_put_contents文件名是第一个参数,第二个是数据。 file_put_contents

file_put_contents($filename, $file);