PHP 比较两个数组,得到匹配的值,而不是差值

2022-08-30 13:02:28

我试图比较两个数组,只得到两个数组上存在的值,但不幸的是,我找不到正确的数组函数来使用...

我找到了功能:http://php.net/manual/en/function.array-diff.phparray_diff()

但这是为了两个数组的差异。

例:

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

答案 1

很简单,请改用 array_intersect() 代替:

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

答案 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