2013-05-05 26 views
10

我对此很陌生,但在尝试提问之前尽量学习。不幸的是,我不太可能有词汇来问清楚的问题。道歉和感谢提前。从单独的文件构建一个PHP数组

是否可以从多个文件中的数据中构建一个数组?假设我有一系列文本文件,每个文件的第一行是三个标签,用逗号分隔,我想将它们存储在所有文本文件中所有标签的数组中,我将如何去关于那个?

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

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。后面跟着爆炸的东西,我发现here

$content = explode(",",$content); 
print $content[0]; 

这没有奏效,很明显,但我无法弄清楚为什么不行。如果我没有解释清楚,那么请提问,以便我可以澄清我的问题。

谢谢你的帮助,亚当。

+2

您可以发布从'mytextfilename.txt'一些示例数据? – 2013-05-05 23:44:04

+1

您还可以添加您的预期输出 – Baba 2013-05-05 23:44:33

+2

您可能希望查看'str_getcsv()'而不是'explode'。要读取多个文件,只需使用'glob()'和'foreach()'来收集列。 - 您仍然需要提及每个文件是否只包含一行内容。否则,一个非常整洁的第一个问题。 – mario 2013-05-05 23:48:16

回答

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); 

既然你长牙..你可以考虑一下这个版本

$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); 
+0

你好,谢谢。是否有可能将其分解来解释每个元素的含义?我对任何一种语言都不熟悉。我查了一些术语,但他们并没有融合在一起(我想你可以说我不知道​​语法)。或者,可以将它放到上下文中,我的意思是,可以将它复制到一个php文件中,制作几个文本文件供它读取并加载到我的服务器上以查看输出是什么?否则我不确定我可以用它做很多事情。 – adamburton 2013-05-06 00:09:34

+0

添加简单的版本,你可以理解 – Baba 2013-05-06 00:14:57

+0

这很好,谢谢。我现在正在通过它,试图弄清楚它。 – adamburton 2013-05-06 00:27:13

相关问题