2011-05-18 102 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