dpdp42233 2017-11-04 17:26
浏览 152
已采纳

在多维数组中查找匹配项

I have an array that contains phone numbers in different format:

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

I need to check if another number is in that array. I assume I need to loop through array and strip all non-numeric values before I compare.

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

I think I'm close but it's not quite there. What am I missing?

  • 写回答

4条回答 默认 最新

  • dongshuo6185 2017-11-04 17:36
    关注

    The phone number is in the key [0] of each first-level array element, so you can't compare each instance of $phone directly. Also, I would replace all non-digit characters so that different notations still turn out as the same number.

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

    this will output:

    not found
    found
    not found
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里