如何检查给定三个数组的条件

How to check the condition in given three array

我有三个数组

  1. 已选择主题
  2. 相关组
  3. topicAssingned
$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 数组中至少应有一个值,基于组 ID(G-001)。 $topicAssingned 在 topics 下,topicID : T-100 是 present ,所以 Disable : D

$topicsSelected 数组值(T-100 或 T-600)$topicAssingned 数组中至少应有一个值,基于组 ID(G-002)。 $topicAssingned under topics , topicID : T-100 & T-600 not present , 所以 Disable : A

预期输出:

[
     "id": "G-001",
    "name": "3 A",
    "active": false,
    "Disable" : "D"
],
[
     "id": "G-002",
    "name": "3 B",
    "active": false,
    "Disable" : "A"
]

My Code

    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);

My Output

    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 — Return 数组的所有键或键的子集

输出

Array
(
    [0] => Array
        (
            [id] => G-001
            [name] => 3 A
            [active] => 
            [disable] => D
        )

    [1] => Array
        (
            [id] => G-002
            [name] => 3 B
            [active] => 
            [disable] => A
        )

)

Demo