我有一個名為“list.txt”的純文本檔案,然后使用 file() 將其內容存盤在變數 $array1 中。文本檔案包含以下內容:
12088
10118
10182
12525
58162
11821
17533
10118
我還宣告了另一個名為 $array2 的陣列變數,其內容類似:
$array2 = array(
'12088',
'10118',
'10182',
'12525',
'58162',
'11821',
'17533',
'10118'
);
當我運行這個函式時,它什么也沒顯示。
$needle = "12088";
if ( in_array($needle, $array1) ) {
echo 'Found in array1!';
}
但是,當我將它交換到 $array2 時,腳本顯示“在 array2 中找到!”。
腳本如下所示:
$array1 = file('list.txt');
$array2 = array(
'12088',
'10118',
'10182',
'12525',
'58162',
'11821',
'17533',
'10118'
);
$needle = "12088";
if ( in_array($needle, $array1) ) {
echo 'Found in array1!';
}
if ( in_array($needle, $array2) ) {
echo 'Found in array2!';
}
這兩個陣列之間的區別是什么導致 $needle 出現在一個陣列中,而不是另一個?
uj5u.com熱心網友回復:
不同之處在于您在 list.txt 中顯示了 \r\n 個符號。
嘗試使用$array1 = array_map('trim', $array1)之前
if ( in_array($needle, $array1) ) {
echo 'Found in array1!';
}
uj5u.com熱心網友回復:
您需要先將檔案轉換為陣列。你可以使用str_getcsv,像這樣:
參考:str_getcsv
$file = file_get_contents('test.txt');
// Separator set as new line "\n"
$array = str_getcsv($file, "\n");
var_dump($array);
// Output
array:8 [▼
0 => "12088"
1 => "10118"
2 => "10182"
3 => "12525"
4 => "58162"
5 => "11821"
6 => "17533"
7 => "10118"
]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/342687.html
