我有三个数组
$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)应基于groupID(G-001)在$ topicAssingned数组中至少存在一个值。 $ topicAssingned在主题下,topicID:T-100 存在,因此Disable : D
$ topicsSelected数组值(T-100或T-600)应基于groupID(G-002)在$ topicAssingned数组中至少存在一个值。 $ topicAssingned在主题下,topicID: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
)
)
答案 0 :(得分:2)
您可以尝试以下代码段,
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
)
)
答案 1 :(得分:0)
目前您根本不使用$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);