dotdx80642 2018-01-12 15:18
浏览 52
已采纳

如何创建一个递归函数来取消PHP中的多维数组?

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?

  • 写回答

3条回答 默认 最新

  • dqrsceg6279196 2018-01-12 15:42
    关注
    function del($target, $candidate) {
        foreach ($target as $key => $value) {
            if (in_array($key, $candidate)) {
                unset($target[$key]);
            } elseif (is_array($value)) {
                $target[$key] = del($value, $candidate);
                if (!count($target[$key])) {
                    unset($target[$key]);
                }
            }
        }
        return $target;
    }
    
    $new = del($target, $candidate);
    var_dump($new);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥50 三种调度算法报错 有实例
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥20 java在应用程序里获取不到扬声器设备