php数组匹配匹配里面的值,php – 比较数组并搜索匹配的值
我有2個(gè)數(shù)組,$arr1和$arr2:
$arr1是我希望從excel文件中讀取的列列表,$arr2是實(shí)際找到的列數(shù)組.
有時(shí)上傳的文件包含
>拼寫錯(cuò)誤的列名稱
>列的順序不同
>可能會(huì)遺漏一些列
>此外,列名可能包含不同字符集中的字母(例如,希臘語’M’看起來像拉丁語M但不能被視為相同).
讓我們說,例如,我們有以下2個(gè)數(shù)組:
$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個(gè)數(shù)組并將匹配元素的位置保存到第3個(gè)數(shù)組:
$arr3 = ([0]=>0, [1]=>1, [2]=>3, [3]=>5, [4]=>6, [5]=>...);
在$arr2中顯示$arr1的每個(gè)匹配元素的位置.
“匹配”是指所有相同的元素(例如Action),或者部分相同(例如Test& Tes),以及那些相似但不同情況的元素(例如Foo& foo,酒吧和酒吧).
我?guī)滋烨鞍l(fā)布了this question,我得到了一個(gè)很好的答案,但經(jīng)過多次測(cè)試后,我發(fā)現(xiàn)它并不總是按預(yù)期工作.
因此,經(jīng)過更多搜索,我找到了levenshtein函數(shù),所以我做了一個(gè)組合,首先檢查完全匹配,如果沒有找到,則嘗試找到最接近的匹配.現(xiàn)在,問題是某些列具有相似的名稱,例如. Catlevel1,Catlevel2,…,Catlevel6.因此,如果缺少Catlevel2,它將與最后一個(gè)&最相似的列是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個(gè)數(shù)組,找到最接近的值匹配并將匹配值鍵保存到第3個(gè)數(shù)組以用作2個(gè)數(shù)組之間的關(guān)鍵引用?
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎(jiǎng)勵(lì)來咯,堅(jiān)持創(chuàng)作打卡瓜分現(xiàn)金大獎(jiǎng)總結(jié)
以上是生活随笔為你收集整理的php数组匹配匹配里面的值,php – 比较数组并搜索匹配的值的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【Python】一道题吃够Python语
- 下一篇: 预充电电路工作原理_常见变频空调室外机电