从单独的文件构造PHP数组

ada*_*ton 10 php arrays

我是新手,但在这里提问之前,我尽可能多地学习.不幸的是,我不太可能有词汇提出明确的问题.提前道歉并表示感谢.

是否可以用几个文件中的数据构建数组?假设我有一系列文本文件,每个文件的第一行是三个标记,用逗号分隔,我希望存储在所有文本文件的所有标记的数组中,我该如何处理?

例如,我的文件可能包含标签,页面标题及其内容:

social movements, handout, international

Haiti and the Politics of Resistance

Haiti, officially the Republic of Haiti, is a Caribbean country. It occupies the western, smaller portion of the island of Hispaniola, in the Greater Antillean archipelago, which it shares with the Dominican Republic. Ayiti (land of high mountains) was the indigenous Taíno or Amerindian name for the island. The country's highest point is Pic la Selle, at 2,680 metres (8,793 ft). The total area of Haiti is 27,750 square kilometres (10,714 sq mi) and its capital is Port-au-Prince. Haitian Creole and French are the official languages.
Run Code Online (Sandbox Code Playgroud)

我想要的结果是一个页面,其中包含所有文本文件中使用的所有标记,每个文本文件都可以单击以查看包含这些标记的所有页面的列表.

现在,没关系,我想要删除重复的标签.我是否需要读取第一个文件的第一行,然后展开该行,然后将这些值写入数组?然后对下一个文件做同样的事情?我试图这样做,首先:

$content = file('mytextfilename.txt');
//First line: $content[0];
echo $content[0];
Run Code Online (Sandbox Code Playgroud)

我在这里找到.接着是我在这里找到的关于爆炸的东西.

$content = explode(",",$content);
print $content[0];
Run Code Online (Sandbox Code Playgroud)

这显然不起作用,但我无法弄明白为什么不这样做.如果我没有很好地解释自己,那么请问我可以尝试澄清我的问题.

亚当,谢谢你的帮助.

Bab*_*aba 3

你可以试试:

$tags = array_reduce(glob(__DIR__ . "/*.txt"), function ($a, $b) {
    $b = explode(",", (new SplFileObject($b, "r"))->fgets());
    return array_merge($a, $b);
}, array());

// To Remove Spaces
$tags = array_map("trim", $tags);

// To make it unique
$tags = array_unique($tags);

print_r($tags);
Run Code Online (Sandbox Code Playgroud)

由于您正在出牙..您可以考虑这个版本

$tags = array(); // Define tags
$files = glob(__DIR__ . "/*.txt"); // load all txt fules in current folder

foreach($files as $v) {
    $f = fopen($v, 'r'); // read file
    $line = fgets($f); // get first line
    $parts = explode(",", $line); // explode the tags
    $tags = array_merge($tags, $parts); // merge parts to tags
    fclose($f); // closr file
}

// To Remove Spaces
$tags = array_map("trim", $tags);

// To make it unique
$tags = array_unique($tags);

print_r($tags);
Run Code Online (Sandbox Code Playgroud)