[英]php foreach or in_array takes only last element of array
請我有大文件的行,我需要在另一個文件中找到與值匹配的文件。
我將txt文件放入數組。
AS11251
AS13379
AS135377
...
AS8972
然后我使用大文件生成器逐行讀取。 每行看起來像這樣(除了前幾行): * 1.0.6.0/24 137.164.16.84 0 0 0 2152 6939 4826 38803 i
然后我將這些行一一取出,將其分解並將其與該數組與 txt 中的值進行比較。 但我只得到與最后一個元素(AS8972)匹配的行。 我試過 foreach,我試過 in_array 但都失敗了。 唯一有效的是一堆 if/elseif 與該 txt 中的每個值。
這是我的代碼:
//first part - txt file into the array
$checklist = function() {
$as_checklist = fopen(__DIR__ . '/as_checklist.txt', 'r');
if (!$as_checklist)
die('file does not exist or cannot be opened');
while (($line_as = fgets($as_checklist)) !== false) {
yield $line_as;
}
fclose($as_checklist);
};
$checklist_array = array();
$i = 0;
foreach ($checklist() as $line_as) {
$checklist_array[$i] = $line_as;
$i++;
}
//end of first part
//second part - generator for huge file, reading line by line
$fileData = function() {
$file = fopen(__DIR__ . '/oix-full-snapshot-latest.dat', 'r');
if (!$file)
die('file does not exist or cannot be opened');
while (($line = fgets($file)) !== false) {
yield $line;
}
fclose($file);
};
//end of second part
unlink('clear_lines.txt');
//third part, checking line by line if there is a match with array from first part
foreach ($fileData() as $nextline) {
set_time_limit(300);
if (substr($nextline, 0, 1) == '*'){
$nextline = preg_replace("/[[:blank:]]+/"," ", $nextline);
$line_array = explode(' ', $nextline);
$count = count($line_array);
$current_AS = "AS" . $line_array[$count-2];
if (in_array($current_AS, $checklist_array)){
//echo $current_AS."<br>";
//echo $line_array[1]." - ".$line_array[2]."<br><br>";
$current_content = $current_AS . " " . $line_array[1] . "\n";
file_put_contents('clear_lines.txt',$current_content, FILE_APPEND);
}
}
}
感謝您的建議,我想這是那個foreach的一些不好的用法,但無法弄清楚
最后一行,分解:
foreach($data1 as $s) {
foreach($data2 as $d) {
// str_replace('AS','',$s) strips out the 'AS' from the search string
// preg_split('/\s+/', $d) returns an array of all the elements of the big data line split by groups of spaces
// in_array() checks if the search string exists in the big data line array
if (in_array(str_replace('AS','',$s), preg_split('/\s+/', $d))) {
$found[]=$d;
}
}
}
代碼,在上下文中
<?php
$data1 = <<<EOT
AS11251
AS13379
AS135377
AS8972
EOT;
$data2 = <<<EOT
* 5.35.224.0/24 212.66.96.126 0 0 0 20912 3257 1299 20773 20773 20773 20773 20773 8972 i
* 1.0.0.0/24 206.24.210.80 0 0 0 3561 209 3356 13335 i
EOT;
$data1 = explode("\n", $data1);
$data2 = explode("\n", $data2);
$found = [];
foreach($data1 as $s) foreach($data2 as $d) if (in_array(str_replace('AS','',$s), preg_split('/\s+/', $d))) $found[]=$d;
print_r($found);
看看它在行動:
示例: https : //www.tehplayground.com/uldljTx1dQpoSwdK
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.