【问题标题】:PHP compare two arrays and get the matched values not the differencePHP比较两个数组并获得匹配的值而不是差异
【发布时间】:2012-04-15 17:16:44
【问题描述】:

我正在尝试比较两个数组并仅获取两个数组上存在的值,但不幸的是,我找不到要使用的正确数组函数...

我找到了array_diff() 函数:http://php.net/manual/en/function.array-diff.php

但这是两个数组的区别。

示例:

$array1 = array("**alpha**","omega","**bravo**","**charlie**","**delta**","**foxfrot**");
$array2 = array("**alpha**","gamma","**bravo**","x-ray","**charlie**","**delta**","halo","eagle","**foxfrot**");

预期输出:

$result = array("**alpha**","**bravo**","**charlie**","**delta**","**foxfrot**");

【问题讨论】:

    标签: php arrays compare match


    【解决方案1】:

    我认为这个问题的更好答案是

    array_diff() 
    

    因为它将数组与一个或多个其他数组进行比较,并返回数组中不存在于任何其他数组中的值。

    array_intersect() 返回一个数组,其中包含所有参数中存在的数组的所有值。请注意,密钥会被保留。

    【讨论】:

      【解决方案2】:

      好的..我们需要比较动态数量的产品名称...

      可能有更好的方法...但这对我有用...

      ... 因为....字符串只是字符数组.... :>}

      //  Compare Strings ...  Return Matching Text and Differences with Product IDs...
      
      //  From MySql...
      $productID1 = 'abc123';
      $productName1 = "EcoPlus Premio Jet 600";   
      
      $productID2 = 'xyz789';
      $productName2 = "EcoPlus Premio Jet 800";   
      
      $ProductNames = array(
          $productID1 => $productName1,
          $productID2 => $productName2
      );
      
      
      function compareNames($ProductNames){   
      
          //  Convert NameStrings to Arrays...    
          foreach($ProductNames as $id => $product_name){
              $Package1[$id] = explode(" ",$product_name);    
          }
      
          // Get Matching Text...
          $Matching = call_user_func_array('array_intersect', $Package1 );
          $MatchingText = implode(" ",$Matching);
      
          //  Get Different Text...
          foreach($Package1 as $id => $product_name_chunks){
              $Package2 = array($product_name_chunks,$Matching);
              $diff = call_user_func_array('array_diff', $Package2 );
              $DifferentText[$id] = trim(implode(" ", $diff));
          }
      
          $results[$MatchingText]  = $DifferentText;              
          return $results;    
      }
      
      $Results =  compareNames($ProductNames);
      
      print_r($Results);
      
      // Gives us this...
      [EcoPlus Premio Jet] 
              [abc123] => 600
              [xyz789] => 800
      

      【讨论】:

        【解决方案3】:

        简单,改用array_intersect()

        $result = array_intersect($array1, $array2);
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2013-04-27
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多