php PHP比较两个数组并获得匹配的值而不是差异
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9969764/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP compare two arrays and get the matched values not the difference
提问by Julian Paolo Dayag
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 the array_diff()
function: http://php.net/manual/en/function.array-diff.php
我找到了array_diff()
函数:http: //php.net/manual/en/function.array-diff.php
But it's for the difference of the both arrays.
但这是为了两个数组的差异。
Example:
例子:
$array1 = array("**alpha**","omega","**bravo**","**charlie**","**delta**","**foxfrot**");
$array2 = array("**alpha**","gamma","**bravo**","x-ray","**charlie**","**delta**","halo","eagle","**foxfrot**");
Expected Output:
预期输出:
$result = array("**alpha**","**bravo**","**charlie**","**delta**","**foxfrot**");
回答by Alix Axel
Simple, use array_intersect()
instead:
简单,array_intersect()
改用:
$result = array_intersect($array1, $array2);
回答by Bill Warren
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