我有2个数组,$arr1和$arr2:
$arr1是我希望从excel文件中读取的列列表,$arr2是实际找到的列数组.
有时上传的文件包含
>拼写错误的列名称
>列的顺序不同
>可能会遗漏一些列
>此外,列名可能包含不同字符集中的字母(例如,希腊语’M’看起来像拉丁语M但不能被视为相同).
让我们说,例如,我们有以下2个数组:
$arr1 = array('Action', 'LotSize', 'QuantityMinimum', 'SupplierName', 'SPN',
'PartNumExt', 'UOM', 'ListPrice', 'MPN', 'MFrName', 'CatLevel1', 'CatLevel2',
'CatLevel3', 'CatLevel4', 'CatLevel5', 'CatLevel6', 'AcctLevel1', 'AcctLevel2',
'AcctLevel3', 'AcctLevel4', 'AcctLevel5', 'AcctLevel6', 'Desc1', 'Desc2', 'PicName',
'SupplierURL', 'CatPart','TechSpec', 'Kad');
$arr2 = array('Action', 'LotSze', 'QuantityMinimum', 'SupplierName', 'SPN',
'PartNumEx', 'UOM', 'ListPric', 'MPN', 'MfrName', 'CatLevel1', 'CatLevel2',
'CatLevel3', 'CatLevel4', 'AcctLevel1', 'AcctLevel2', 'AcctLevel3', 'AcctLevel4',
'Desc1', 'Desc2', 'PicName', 'SupplierURL', 'CatPart');
我需要比较2个数组并将匹配元素的位置保存到第3个数组:
$arr3 = ([0]=>0, [1]=>1, [2]=>3, [3]=>5, [4]=>6, [5]=>...);
在$arr2中显示$arr1的每个匹配元素的位置.
“匹配”是指所有相同的元素(例如Action),或者部分相同(例如Test& Tes),以及那些相似但不同情况的元素(例如Foo& foo,酒吧和酒吧).
我几天前发布了this question,我得到了一个很好的答案,但经过多次测试后,我发现它并不总是按预期工作.
因此,经过更多搜索,我找到了levenshtein函数,所以我做了一个组合,首先检查完全匹配,如果没有找到,则尝试找到最接近的匹配.现在,问题是某些列具有相似的名称,例如. Catlevel1,Catlevel2,…,Catlevel6.因此,如果缺少Catlevel2,它将与最后一个&最相似的列是Catlevel6.
这是我到目前为止:
foreach($all_columns as $i => $val1) {
$result = null;
// Search the second array for an exact match, if found
if(($found = array_search($val1,$_SESSION['found_columns'],true)) !==false) {
$result = $found;
} else {
// Otherwise, see if we can find a case-insensitive matching string
//where the element from $arr2 is found within the one from $arr1
foreach( $_SESSION['found_columns'] as $j => $val2) {
if($val1<>'' && $val2<>'') {
if( stripos( $val1, $val2) !== false ) {
$result = $j;
break;
} else {
$notfound .= $val1.', ';
break;
}
}
}
}
$_SESSION['found_column_positions'][$i] = $result;
}
/*****ALTERNATIVE METHOD USING levenshtein*****/
$i=0;
foreach($all_columns as $key => $value) {
$found = wordMatch($value, $arr2, 2);
$pos = array_search($found, $_SESSION['found_columns']);
$_SESSION['found_column_positions'][$i] = $pos;
$i++;
}
function wordMatch($input, $array, $sensitivity){
$words = $array;
$shortest = -1;
foreach ($words as $word) {
$lev = levenshtein($input, $word);
if ($lev == 0) {
$closest = $word;
$shortest = 0;
break;
}
if ($lev <= $shortest || $shortest < 0) {
$closest = $word;
$shortest = $lev;
}
}
if($shortest <= $sensitivity){
return $closest;
} else {
return 0;
}
}
是否有更好的方法来比较2个数组,找到最接近的值匹配并将匹配值键保存到第3个数组以用作2个数组之间的关键引用?