我是新手,但在此处提问之前我已尝试尽可能多地学习。不幸的是,我不太可能有足够的词汇来问一个明确的问题。提前致歉并致谢。
是否可以用来自多个文件的数据构建一个数组?假设我有一系列文本文件,每个文件的第一行是三个 标签,用逗号分隔,我想将它们存储在所有文本文件中所有标签的数组中,我该怎么做?
例如我的文件可能包含标签、页面标题及其内容:
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.
我想要的结果是一个包含所有文本文件中使用的所有标签的页面,每个文本文件都可以单击以查看包含这些标签的所有页面的列表。
暂时不要介意我要删除重复的标签。我是否需要读取第一个文件的第一行,展开该行,然后将这些值写入数组?然后对下一个文件做同样的事情?我试图这样做,首先:
$content = file('mytextfilename.txt');
//First line: $content[0];
echo $content[0];
我发现 here .接下来是我发现的关于 explode 的东西 here .
$content = explode(",",$content);
print $content[0];
这显然行不通,但我无法弄清楚为什么不行。如果我没有很好地解释自己,那么请提问,以便我可以尝试澄清我的问题。
谢谢你的帮助,亚当。
最佳答案
你可以试试:
$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);
既然你长牙..你可以考虑这个版本
$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);
关于php - 从单独的文件构建 PHP 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16390280/