簡體   English   中英

在 PHP 中的兩個 arrays 中搜索相同的值

[英]Search for identical values ​within two arrays in PHP

我想在 PHP 中購買兩個 email arrays 時遇到問題,電子郵件在 TXT 內。

output txt 文件:

mm2@m.com
m77@m.com
m77@m.com
mm44@m.com

並且,注冊文件:

mm2@m.com
m77@m.com
m77@m.com
mm44@m.com
cristian@cristian.com
hola@hola.com

而且,這是我嘗試使用的代碼:

$limpios = array('salida.txt'); // Utilizo el archivo generado de la salida para comparar con los registrados.
$reg = array('registrados.txt'); // File para comprar los registros (usuarios registrados);
$registrado = 0;
$registrados = array_intersect($limpios, $reg);
foreach($registrados as $values){
    echo $values;
    $registrado++;
}

echo 'Usuarios registrados(coincidencias entre los dos archivos): ' . $registrado;

哪個輸出:

salida.txtUsuarios registrados(coincidencias entre los dos archivos): 1

您可以給我任何解決方案或想法嗎?

不能text file的內容直接加載到數組中。 你的代碼array('salida.txt'); 只會創建一個值為salida.txtarray

正確的做法是,

讀取兩個文件的內容,並推入 arrays,

$limpios = [];

// Read Content
$content = strtok(file_get_contents('salida.txt'), "\n");

// Push Each line into an array
while ($content !== false) {
    array_push($limpios, $content);
}

$reg = [];

// Read Content
$content = strtok(file_get_contents('registrados.txt'), "\n");

// Push Each line into an array
while ($content !== false) {
    array_push($limpios, $content);
}

注意寫一個普通的 function 讀取內容並壓入數組,防止代碼重復。

現在你可以繼續你的邏輯,

$registrado = 0;
$registrados = array_intersect($limpios, $reg);
foreach($registrados as $values){
    echo $values;
    $registrado++;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM