php数组匹配匹配里面的值,php – 比较数组并搜索匹配的值

我有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个数组之间的关键引用?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值