代码之家  ›  专栏  ›  技术社区  ›  Alex Pliutau

层次结构数组中的php移位

  •  0
  • Alex Pliutau  · 技术社区  · 14 年前

    我有下一个数组:

    Array(
       [id] => 1
       [children] => Array(
          [2] => Array(
             [id] => 2
             [inactive] => true
             [children] => Array(
                [4] => Array(
                   [id] => 4
                   [children] => Array()
                )
             )
          )
          [3] => array(
             [id] => 3
             [children] => Array(
                [5] => Array(
                   [id] => 5
                   [inactive] => true
                   [children] => Array()
                )
             )
          )
       )
    )
    

    我需要从这个数组中删除元素,其中[非活动]=true。但我的问题在下一个。我应该移动数组元素。 输出应为:

    Array(
       [id] => 1
       [children] => Array(
          [4] => Array(
             [id] => 4
             [children] => Array()
          )
          [3] => array(
             [id] => 3
             [children] => Array(
             )
          )
       )
    )
    

    public function deleteInactive($userTree)
    {
        if (!empty($userTree)) {
            foreach($userTree['children'] as $userId => &$user) {
                if (array_key_exists('inactive', $user)) {
                    $userTree['children'] += $user['children'];
                    unset($userTree['children'][$userId]);
                    $this->deleteInactive($userTree);
                    break;
                }
                $this->deleteInactive($user);
            }
        }
        return $userTree;
    }
    

    2 回复  |  直到 14 年前
        1
  •  1
  •   Viper_Sb    14 年前

    <?php
    function deleteInactive($children) {
        $copy = $children;
        foreach ($copy as $key => $child) {
            if (!empty($child['inactive']) && $child['inactive'] === true) {
                unset($children[$key]);
                $children = deleteInactive($child['children']);
            } elseif (!empty($child['children']) && is_array($child['children'])) {
                $children[$key]['children'] = deleteInactive($child['children']);
            }
        }
        return $children;
    } ?>
    

    deleteInactive(array('1' => $array));
    
        2
  •  1
  •   Ward Bekker    14 年前