2011-05-18 46 views
1

我有一個名爲data.txt的平面文件。每行包含四個條目。如何檢查數組中是否存在變量?

的data.txt

blue||green||purple||primary 
green||yellow||blue||secondary 
orange||red||yellow||secondary 
purple||blue||red||secondary 
yellow||red||blue||primary 
red||orange||purple||primary 

我試過這個,看看是否變「黃」的存在是爲任何線的第一個條目:

$color = 'yellow'; 

$a = array('data.txt'); 

if (array_key_exists($color,$a)){ 
// If true 
    echo "$color Key exists!"; 
    } else { 
// If NOT true 
    echo "$color Key does not exist!"; 
    } 

,但它無法正常工作如預期。我可以改變什麼來實現這個目標?謝謝....

回答

2

下面利用preg_grep,其執行一個陣列的每個元件上的正則表達式搜索(在這種情況下,該文件的行):

$search = 'yellow'; 
$file = file('file.txt'); 

$items = preg_grep('/^' . preg_quote($search, '/') . '\|\|/', $file); 

if(count($items) > 0) 
{ 
    // found 
} 
+0

雖然這會錯誤地匹配任何前綴換句話說,如果這個例子只是被設計出來的,即'$ search ='yell''會匹配'yellow'作爲第一個字,那麼需要改變正則表達式以確保分隔符跟隨或線路終端 – Orbling 2011-05-19 00:34:11

+0

@ Orbling:感謝那個忽略。更新。 – 2011-05-19 00:35:58

0
$fh = fopen("data.txt","r"); 
$color = 'yellow'; 
$test = false; 

while(($line = fgets($fh)) !== false){ 
    if(strpos($line,$color) === 0){ 
     $test = true; 
     break; 
    } 
} 

fclose($fh); 
// Check $test to see if there is a line beginning with yellow 
0

您的文件中的數據未加載到$a。嘗試

$a = explode("\n", file_get_contents('data.txt')); 

加載它,然後檢查與每個行:

$line_num = 1; 
foreach ($a as $line) { 
    $entries = explode("||", $line); 
    if (array_key_exists($color, $entries)) { 
     echo "$color Key exists! in line $line_num"; 
    } else { 
     echo "$color Key does not exist!"; 
    } 
    ++$line_num; 
} 
+0

此代碼顯示:警告:explode()需要至少2個參數,第1行在/www/tests/mobilestimulus/array_tests/index1.php中給出警告:在/ www/tests/mobilestimulus/array_tests中爲foreach index1.php on line 13 – mobilestimulus 2011-05-19 00:11:25

+0

@mobilestimulus我寫了這段代碼wi沒有測試它。我錯過了第一個爆炸的第一個參數分隔符(「\ n」 - 新行字符)。它應該現在正常工作。 – 2011-05-19 04:10:34

0

線:

$a = array('data.txt'); 

在它僅創建與一個值的數組: '的data.txt' 。在檢查值之前,您需要先閱讀並解析文件。

0

那麼,這不是你如何將文本文件中的單獨數據列表加載到數組中。

另外array_key_exists()只檢查鍵,而不是數組的值。

嘗試:

$lines = file('data.txt', FILE_IGNORE_NEW_LINES); 

$firstEntries = array(); 

foreach ($lines as $cLine) { 
    $firstEntries[] = array_shift(explode('||', $cLine)); 
} 

$colour = 'yellow'; 

if (in_array($colour, $firstEntries)) { 
    echo $colour . " exists!"; 
} else { 
    echo $colour . " does not exist!"; 
} 
+0

即使黃色不是行上的第一個條目,此代碼將返回「存在」 – mobilestimulus 2011-05-19 00:16:22

+0

@mobilestimulus:沒有注意到「FIRST」約束,我會更新它 – Orbling 2011-05-19 00:28:58