PHP-如何部分比较2个数组中的元素 [英] PHP - How do I partially compare elements in 2 arrays
问题描述
我有2个数组:
$arr1 = array('Test', 'Hello', 'World', 'Foo', 'Bar1', 'Bar'); and
$arr2 = array('hello', 'Else', 'World', 'Tes', 'foo', 'BaR1', 'Bar');
我需要比较2个数组并将匹配元素的位置保存到第3个数组 $ arr3 =(3,0,2,4,4,5,6); //期望的结果,显示$ arr1的匹配元素在$ arr2中的位置。
I need to compare the 2 arrays and save the position of the matching elements to a 3rd array $arr3 = (3, 0, 2, 4, 5, 6); //expected result, displaying position of matching element of $arr1 in $arr2.
匹配是指所有相同的元素(例如世界),或部分相同(例如Test& Tes),以及那些相似但大小写不同的元素(例如Foo& foo,Bar& bar)。
By 'matching' I mean all elements that are identical (ex. World), or partially the same (ex. Test & Tes) and also those elements that are alike but are in different case (ex. Foo & foo, Bar & bar).
我已经尝试了一系列组合和各种功能,但均未成功,使用了 array_intersect(),substr_compare(),array_filter()
及更多。我不是要确切的解决方案,只是要让我走上正轨,因为我整个下午都在兜圈子。
I've tried a series of combinations and of various functions without success, using functions like array_intersect(), substr_compare(), array_filter()
and more. I'm not asking for the exact solution, just something to get me on the right track because i'm going around in circles all afternoon.
推荐答案
这似乎对我有用,但是我确定我缺少一些极端的情况,因此您需要测试以下内容:
This seemed to work for me, but I'm sure there are some edge cases I'm missing that you'd need to test for:
foreach( $arr1 as $i => $val1) {
$result = null;
// Search the second array for an exact match, if found
if( ($found = array_search( $val1, $arr2, true)) !== false) {
$result = $found;
} else {
// Otherwise, see if we can find a case-insensitive matching string where the element from $arr2 is at the 0th location in the one from $arr1
foreach( $arr2 as $j => $val2) {
if( stripos( $val1, $val2) === 0) {
$result = $j;
break;
}
}
}
$arr3[$i] = $result;
}
Array ( [0] => 3 [1] => 0 [2] => 2 [3] => 4 [4] => 5 [5] => 6 )
这篇关于PHP-如何部分比较2个数组中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!