簡體   English   中英

在多維數組中查找匹配項

[英]Find matches in multidimensional array

我有一個數組,其中包含不同格式的電話號碼:

$myArr[0][0] == '122-33-2222';
$myArr[1][0] == '(122) 433-5555';
$myArr[2][0] == '122 644.8888';

我需要檢查另一個數字是否在該數組中。 我假設我需要遍歷數組並在比較之前剝離所有非數字值。

$findNumber = 122.433.5555;
$varPhone = preg_replace("/[^0-9,.]/", "", $findNumber);

foreach ($myArr AS $phone) {
   if (preg_replace("/[^0-9,.]/", "", $phone) == $varPhone) {
      echo "found";
   } else {
      echo "not found";
   }
}

我想我已經接近了,但還不在那里。 我想念什么?

您的代碼存在一些問題,請嘗試以下操作:

$myArr[0][0] = '122-33-2222';
$myArr[1][0] = '(122) 433-5555';
$myArr[2][0] = '122 644.8888';

$findNumber = "122.433.5555";

$varPhone = preg_replace("/[^0-9]/", "", $findNumber);

foreach ($myArr AS $phone)
{
   $phone = preg_replace("/[^0-9]/", "", $phone);

   if ($phone[0] == $varPhone)
   {
        echo "found";
   }
   else
   {
      echo "not found";
   }
}

取出,. 從正則表達式開始,由於$phone是一個數組,因此應將其視為。

輸出:

not foundfoundnot found

電話號碼位於每個第一級數組元素的鍵[0]中,因此您不能直接比較$phone每個實例。 另外,我將替換所有非數字字符,以便不同的符號仍顯示為相同的數字。

<?php
// initialize array for the sake of this demo, to make this snippet work
$myArr = array(array(), array(), array());
$myArr[0][0] = '122-33-2222';
$myArr[1][0] = '(122) 433-5555';
$myArr[2][0] = '122 644.8888';

$findNumber = "122.433.5555";

function cleanNumber($in) {
  return preg_replace("/[^0-9]/", "", $in);
}

foreach ($myArr AS $phone) {
   // the number is in the key [0] for each first-level array element
   if (cleanNumber($phone[0]) == cleanNumber($findNumber)) {
      echo "found<br>";
   } else {
      echo "not found<br>";
   }
}

這將輸出:

not found
found
not found

請檢查以下可能有效的代碼段

<?php
$myArr[0] = '122-33-2222';
$myArr[1] = '(122) 433-5555';
$myArr[2]    = '122 644.8888';

$findNumber = "122.433.5555";
$varPhone = preg_replace("/[^0-9]/", "", $findNumber);
$flag = false;
foreach ($myArr AS $phone) {
   if (preg_replace("/[^0-9]/", "", $phone) == $varPhone) {
      $flag = true;
      break;

   } 
}

if($flag)
    echo "found";
else
    echo "not found";

?>

更改:-$ myArr應該是1d數組,而不是2d數組,

==是比較運算符,應改用賦值運算符。

在preg_replace中,即使點也應替換為空

這是您的代碼的工作示例:

$myArr[0][0] = '122-33-2222';
$myArr[1][0] = '(122) 433-5555';
$myArr[2][0] = '122 644.8888';

$findNumber = '122.433.5555';
$normalize = preg_replace("/[^0-9]/","", $findNumber);

$found = false;
foreach ($myArr AS $phone) {
  if ($normalize == preg_replace("/[^0-9]/","", $phone[0])) {
    $found = true;
    break;
  }
}

echo $found;

更好的方法是使用array_filter

$myArr[0][0] = '122-33-2222';
$myArr[1][0] = '(122) 433-5555';
$myArr[2][0] = '122 644.8888';

$findNumber = '122.433.5555';
$normalize = preg_replace("/[^0-9]/","", $findNumber);

$filtered =array_filter($myArr, function ($phone) use ($normalize) {
  return preg_replace("/[^0-9]/","", $phone[0]) == $normalize;
});

var_dump($filtered);
echo sizeof($filtered);

暫無
暫無

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

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