2015-01-09 36 views
-2

我從文件中使用PHP讀取:如何分裂PHP數組,以便每個值可以被訪問

$file = file('myfile.txt'); 

此存儲每個線在線陣列中的單獨的值。

myfile.txt的

123-12333 : Example 
456-45666 : MyWorld 

這一結果是:

Array([0] => 123-12333 : Example [1] => 456-45666 : MyWorld) 

我需要拆分每個單獨的索引值,使我的結果將最終會被這樣的事情:

Array([0] => 123-12333 [1] => : [2] => Example [3] => 456-45666 [4] => : [5] => MyWorld) 

我需要分割數組,以便每個值都可以獨立訪問。

array_chunk似乎不工作,並且array_slice也無濟於事。有什麼建議麼??

事情我已經試過是:

print_r(array_chunk($fileContents,2)); 

結果:

Array ([0] => Array ([0] => 123-12333 : Duan Uys [1] => 345-34555 : Dennis Taylor) [1] => Array ([0] => 555-55555 : Darwin Award)) 
+3

請分享你已經嘗試過。 –

+0

'array_walk($ file,function(&$ value){$ value = explode('',$ value);})'可能是一個起點 –

+0

爲什麼downvote這個答案? – macas

回答

1

嘗試了這一點:

$file  = file('myfile.txt'); 
$splitted = array(); 
foreach ($file as $line) { 
    $splitted = array_merge($splitted, explode(' ', $line)); 
} 
//now $splitted will have the format you need 
+0

如何分割「:」,分割一個空格會給他們3個條目,而不是2預期 –

+1

@Hanky웃Panky OP實際上希望將':'存儲爲一個單獨的值(即'Array([ 0] => 123-12333 [1] =>:...)')雖然我不知道爲什麼這會有用... – War10ck

+0

我需要隔離123-12333,這就是爲什麼我需要它們所有分開。謝謝@waldson這個解決方案爲我工作。 – macas

0

的myfile.txt:

123-12333 : Example 
456-45666 : MyWorld 

PHP:

$file = 'myfile.txt'; 
$content = file_get_contents($file); 
$lines = explode("\n", $content); 
$returnArray = array(); 
foreach ($lines as $line) { 
    $returnArray[] = explode(' ', $line); 
} 

print_r($returnArray); 

正如你在留言中提到你所需要的第一部分。爲了得到這個,變化:

$returnArray[] = explode(' ', $line);  

到:

$returnArray[] = current(explode(' ', $line)); 
+1

您的$ returnArray將只包含最後一行數據。你在每一個循環都覆蓋它。 –

+0

@WaldsonPatricio我看到了我的錯誤並修復了它 – Peter

0

您可以將每個部分傳遞給一個變量爲一個字符串,然後分裂成「:」 dilimiter,然後把它像一個數組這樣的:

$output=array(); 
foreach ($input as $key=>$value){ 
    $output[$key][]=substr($value,0,strpos($value,' : ')); 
    $output[$key][]=substr($value,strpos($value,' : ')+3,strlen($value)); 
} 
0

怎麼樣fscanf行動......其實這就是它的預期如何使用:

$handle = fopen("myfile.txt", "r"); 
$lines = array(); 

while ($line = fscanf($handle, "%s : %s\n")) { 
    array_merge($lines, $line); 
} 

fclose($handle); 

這將省去結腸,但我不認爲這就是有用的,因爲你說:

我需要在123-12333隔離開來,這就是爲什麼我需要他們全部分隔。

此使用file,然後遍歷和修改的東西,但它有讓整個事情的心不是在內存中的第一逐行讀取文件中的行的好處是非常相似的其他方法。如果你的文件非常小,這將無關緊要,但是如果這個文件很大或者隨着時間的推移會變大。此外,如果你只想要的號碼,那麼你可以做:

$handle = fopen("myfile.txt", "r"); 
$numbers = array(); 

while ($line = fscanf($handle, "%s : %s\n")) { 
    $numbers[] = $line[0]; 
} 

fclose($handle); 
相關問題