PHP compare two arrays and get the matched values not the difference

后端 未结 2 910
悲&欢浪女
悲&欢浪女 2020-12-08 19:26

I\'m trying to compare two arrays and get only the values that exist on both arrays but, unfortunately, I can\'t find the right array function to use...

I found th

相关标签:
2条回答
  • 2020-12-08 20:06

    OK.. We needed to compare a dynamic number of product names...

    There's probably a better way... but this works for me...

    ... because....Strings are just Arrays of characters.... :>}

    //  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
    
    0 讨论(0)
  • 2020-12-08 20:23

    Simple, use array_intersect() instead:

    $result = array_intersect($array1, $array2);
    
    0 讨论(0)
提交回复
热议问题