简介 - 此问题已于 2018 年 5 月 27 日更新:
我有 1PHP多维数组,包含6个子数组,每个子数组包含20个子子数组,每个子数组又包含2个子子数组,一个是字符串(header),另一个是未指定数量的关键字(keywords )。
我希望将 120 个子子数组中的每一个与剩余 5 个子数组中包含的 100 个其他子子数组进行比较。以便子子数组1
我会尝试一下!
我使用 preg_grep 查找其他子数组中相同的项目。然后我使用 count 来查看有多少个匹配的关键字。
这就是门槛所在。目前我将其设置为2
,这意味着两个匹配的关键字是匹配的。
//flatten array to make it simpler
$new =[];
foreach($array as $subarr){
$new = array_merge($new, $subarr);
}
$threshold = 2;
$merged=[];
foreach($new as $key => $story){
// create regex pattern to find similar items
$words = "/" . implode("|", $story["keywords"]) . "/i";
foreach($new as $key2 => $story2){
// only loop new items and items that has not been merged already
if($key != $key2 && $key2 > $key && !in_array($key2, $merged)){
// If the count of words from preg_grep is above threshold it's mergable
if(count(preg_grep($words, $story2["keywords"])) > $threshold){
// debug
//echo $key . " " . $key2 . "\n";
//echo $story["header"] . " = " . $story2["header"] ."\n\n";
// if the item does not exist create it first to remove notices
if(!isset($res[$key])) $res[$key] = ["header" => [], "keywords" =>[]];
// add headers
$res[$key]["header"][] = $story["header"];
$res[$key]["header"][] = $story2["header"];
// only keep unique
$res[$key]["header"] = array_unique($res[$key]["header"]);
// add keywords and remove duplicates
$res[$key]["keywords"] = array_merge($res[$key]["keywords"], $story["keywords"], $story2["keywords"]);
$res[$key]["keywords"] = array_unique($res[$key]["keywords"]);
// add key2 to merged so that we don't merge this again.
$merged[] = $key2;
}
}
}
}
var_dump($res);
https://3v4l.org/6cKRq https://3v4l.org/6cKRq
输出正如您所讨论的“想要的”。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)