我有三个阵列
$topicsSelected = [ "T-100","T-600"];
$relavantGroups = [[ "id" => "G-001","name" => "3 A","active"=> false ], ["id"=> "G-002","name"=> "3 B","active"=> false] ];
$topicAssingned = [
"G-001" => [
"groupID" => "G-001",
"groupName" => "3 A",
"topics" => [
"T-100" => [
"topicID" => "T-100"
],
"T-200" => [
"topicID" => "T-200"
]
]
],
"G-002" => [
"groupID" => "G-002",
"groupName" => "3 B",
"topics" => [
"T-400" => [
"topicID" => "T-400"
],
"T-500" => [
"topicID" => "T-500"
]
]
],
];
$ topicsSelected数组值(T-100或T-600)$ topicAssingned数组中至少应有一个值,基于groupID(G-001)。 $ topicAssned主题下,topicID:T-100存在,所以Disable : D
$ topicsSelected数组值(T-100或T-600)$ topicAssingned数组中至少应有一个值,基于groupID(G-002)。 $ topic主题下的主题,主题ID:T-100和T-600不存在,所以Disable : A
预期产量:
[
"id": "G-001",
"name": "3 A",
"active": false,
"Disable" : "D"
],
[
"id": "G-002",
"name": "3 B",
"active": false,
"Disable" : "A"
]
我的守则
foreach ($relavantGroups as &$g) {
$found = false;
foreach ($topicAssingned as $key => $assigned) {
if ($key === $g["id"]) {
$found = true;
break;
}
}
$g["disable"] = $found ? "D" : "A";
}
echo "<pre>";
print_r($relavantGroups);
我的输出
Array
(
[0] => Array
(
[id] => G-001
[name] => 3 A
[active] =>
[disable] => D
)
[1] => Array
(
[id] => G-002
[name] => 3 B
[active] =>
[disable] => D
)
)
你可以尝试这个片段,
foreach ($relavantGroups as &$g) {
$found = false;
foreach ($topicAssingned as $key => $assigned) {
if ($key === $g["id"]) {
$temp = array_keys($assigned['topics']); // fetching all topic ids
$intr = array_intersect($topicsSelected, $temp); // checking if there are any matching values between topicSelected and traversed values
$found = (!empty($intr) ? true : false); // if found return and break
break;
}
}
$g["disable"] = $found ? "D" : "A";
}
print_r($relavantGroups);
array_intersect - 计算数组的交集 array_keys - 返回数组的所有键或键的子集
产量
Array
(
[0] => Array
(
[id] => G-001
[name] => 3 A
[active] =>
[disable] => D
)
[1] => Array
(
[id] => G-002
[name] => 3 B
[active] =>
[disable] => A
)
)
目前你根本不使用$topicsSelected
数组 - 你只需要找到ID,然后将其标记为找到。相反,一旦找到该项目,您就需要检查该项是否在该项目的主题列表中。
由于您将ID作为$topicAssingned
变量的关键,因此您无需搜索它,只需按键引用它,然后使用array_keys()
提取主题列表。然后你可以使用array_intersect()
检查它们是否匹配...
foreach ($relavantGroups as &$g) {
// List of topics in assigned
$listTopics = array_keys($topicAssingned[$g["id"]]["topics"]);
// Check for match between selected and topics in group
$g["disable"] = array_intersect($topicsSelected, $listTopics) ? "D" : "A";
}
echo "<pre>";
print_r($relavantGroups);