在多维数组中查找匹配项

时间:2017-11-04 17:26:11

标签: php arrays

我有一个包含不同格式的电话号码的数组:

$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";
   }
}

我认为我很接近,但它并不完全存在。我错过了什么?

4 个答案:

答案 0 :(得分:2)

您的代码存在一些问题,请尝试以下方法:

$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

答案 1 :(得分:1)

电话号码位于每个第一级数组元素的键[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

答案 2 :(得分:1)

请检查以下可能有用的代码段

<?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中的

偶数点应该用空

替换

答案 3 :(得分:0)

以下是您的代码的工作示例:

$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);