Below is my target array which I would like to unset its elements by key based on the candidate array element.
$target = [
60 => "Home"
"Villa" => [
"30" => "Vi",
],
70 => "A",
40 => "B",
50 => "C",
"Land" => [
1 => "La",
35 => "Lb",
37 => "Lc",
39 => "Ld",
],
];
$candidate = [30, 50, 35, 37];
Below is the result that I want after unsetting.
$target = [
60 => "Home"
70 => "A",
40 => "B",
"Land" => [
1 => "La",
39 => "Ld",
],
];
'Villa' must also be gone because it's empty after it's element "30" => "Vi" has been unset.
Below my solution in for-loop.
foreach ($target as $id => $option) {
if (isset($candidate[$id])) {
unset($target[$id]);
}
elseif (is_array($option)) {
foreach ($option as $sub_id => $opt) {
if (isset($candidate[$sub_id])) {
unset($target[$id][$sub_id]);
}
}
}
if (!count($target[$id])) {
unset($target[$id]);
}
}
How can I replace this for-loop in a recursive solution?