2013-05-05 24 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

相關問題