我希望$ Array2中的歌曲标题按$ Array1的顺序排序,而不会丢失$ Array2中的值。 $ Array2中的值应遵循$ Array2中每个键的新顺序。我相信我提供的当前功能是一个坚实的开始......
我有两个数组(请注意每个数组的差异):
例如......
$ Array1包含:
Array ( [0] => 3oh!3 - Don't Trust me [1] => Taylor Swift - You Belong with me [2] => Sean Kingston - Fire Burning [3] => Green Day - Know Your Enemy [4] => Kelly Clarkson - Gone )
$ Array2包含:
Array ( [Taylor Swift - You Belong With Me] => bbbbbb [Sean Kingston - Fire Burning] => cccccc [Kelly Clarkson - Gone] => eeeeee [3OH!3- Don't Trust Me lyrics] => aaaaaa [Green Day Know Your Enemy Official] => dddddd )
我已经启动了一个在本网站上找到的功能:
function sortArrayByArray(array $toSort, array $sortByValuesAsKeys)
{
$commonKeysInOrder = array_intersect_key(array_flip($sortByValuesAsKeys), $toSort);
$commonKeysWithValue = array_intersect_key($toSort, $commonKeysInOrder);
$sorted = array_merge($commonKeysInOrder, $commonKeysWithValue);
return $sorted;
}
...然而
$sortArray = sortArrayByArray($Array2, $Array1);
print_r($sortArray);
$sortArray
只会返回两个结果:
Array
(
[Sean Kingston - Fire Burning] => cccccc
[Kelly Clarkson - Gone] => eeeeee
)
答案 0 :(得分:2)
这是一个解决方案:
<?php
$array1 = array(
0 => '3oh!3 - Don\'t Trust me',
1 => 'Taylor Swift - You Belong with me',
2 => 'Sean Kingston - Fire Burning',
3 => 'Green Day - Know Your Enemy',
4 => 'Kelly Clarkson - Gone',
);
$array2 = array(
'Taylor Swift - You Belong With Me' => 'bbbbbb',
'Sean Kingston - Fire Burning' => 'cccccc',
'Kelly Clarkson - Gone' => 'eeeeee',
'3OH!3- Don\'t Trust Me lyrics' => 'aaaaaa',
'Green Day Know Your Enemy Official' => 'dddddd'
);
// Find matching song titles (case insensitive).
$tmp = array_values(array_uintersect($array1, array_flip($array2), 'strcasecmp'));
if ( ! empty($tmp) )
{
// Generate the array.
$matches = array_flip(array_uintersect(array_flip($array2), $tmp, 'strcasecmp'));
print_r($matches);
}
else
echo 'No matches found.';
?>
这将输出:
Array
(
[Taylor Swift - You Belong With Me] => bbbbbb
[Sean Kingston - Fire Burning] => cccccc
[Kelly Clarkson - Gone] => eeeeee
)
其他2场比赛并非100%完全相同。正如其他人所建议的那样,您可以使用similar_text()
或其他函数来确定两个字符串的相似程度。如果你想这样做,你可以更改array_uintersect
调用中的'strcasecmp'
并编写自己的函数,而不是使用similar_text
(或其他函数)决定是否使用{{1}}实际上,值确实相交或不相交。
答案 1 :(得分:0)
尝试使用Levenshtein distance或similar_text函数之类的函数来比较数组中的字符串。您只需要确定一个尽可能准确匹配的阈值,并且误报率最低。