我有两个URL数组:ArrayA和ArrayB。我需要知道ArrayB的哪些URL(可能有多次出现相同的URL)与ArrayA的哪些URL(此处的URL是唯一的)相匹配。
我将通过foreach循环遍历ArrayB并尝试匹配网址。
ArrayA包含以下网址:
ArrayB包含以下网址:
我想将ArrayB中的每个URL匹配到ArrayA中的正确URL,并在找到匹配项后立即对其执行操作(因此无需保存任何内容)。 ArrayB中的一条路由始终仅与ArrayA中的一条路由匹配(因此n:1关系)。
$arrayA = getPossibleRoutes();
$arrayB = getActivatedRoutes();
// YOUR CODE
我希望创建一个foreach循环(最有可能嵌套的一个循环),该循环遍历ArrayA或ArrayB并在找到匹配项后立即执行操作。
答案 0 :(得分:1)
尝试:
foreach($arrayA as $item){
$patterns[$item] = preg_replace(['/(\{\w*\})/','/\//'],['\d+','\/'],$item);
}
foreach ($arrayB as $arr) {
foreach($patterns as $route => $pattern){
if (preg_match('/^'.$pattern.'$/', $arr))
{
//the matched route is $route
}
}
}
答案 1 :(得分:0)
您可以执行以下操作:
<?php
$arrayA = [
"clients/{client_id}",
"activities/{activity_id}",
"activities/{activity_id}/edit",
"test/{test}/test",
"random/random/{random_id}",
"clients/{client_id}/projects/{project_id}",
"unmatched/path",
];
$arrayB = [
"clients/123/projects/23",
"clients/5/projects/12",
"clients/1",
"clients/52",
"activities/52",
"random/random/1",
"activities/35",
"activities/52/edit",
"test/1/test",
"activities/35/edit",
"not_found_url/35"
];
foreach($arrayA as $arr) {
$key = substr_count($arr, '/');
$getFirstWord = explode("/",$arr);
$sortedA[$getFirstWord[0]][$key] = $arr;
}
foreach($arrayB as $arr) {
$getFirstWord = explode("/",$arr);
if(array_key_exists($getFirstWord[0],$sortedA)) {
$urls[$arr] = $sortedA[$getFirstWord[0]][substr_count($arr, '/')];
}
}
foreach($urls as $key => $url)
print_r($key." => ".$url."<br>");
?>
输出将是:
clients/123/projects/23 => clients/{client_id}/projects/{project_id}
clients/5/projects/12 => clients/{client_id}/projects/{project_id}
clients/1 => clients/{client_id}
clients/52 => clients/{client_id}
activities/52 => activities/{activity_id}
random/random/1 => random/random/{random_id}
activities/35 => activities/{activity_id}
activities/52/edit => activities/{activity_id}/edit
test/1/test => test/{test}/test
activities/35/edit => activities/{activity_id}/edit
编辑:此代码现在应该是动态的,对于任意数量的url /路径。它还支持未找到的URL和/或路径。 编辑2:优化