views:

39

answers:

2

Hello. I have the next array:

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

I need to remove elements from this array, which have [inactive] = true. But my problem in the next. I should shift the array elements. Output should be:

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

It is my function. But it removes array element with all his subelements.

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

Can you help me to modify this function?

Thank you very much.

+1  A: 

Before unsetting a node, you need to attach the children to the parent of the node. This doesn't happen (the code only unsets), so the children are lost.

WardB
Thanks. See my edited function. But it isn't work. It is remove first element, and attach the children. But it make it only with first inactive element.
Alexander.Plutov
+1  A: 

Try this function, it should do as you asked.

<?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;
} ?>

Your FIRST array MUST be a valid children array also, you can call it like this against your array you listed.

deleteInactive(array('1' => $array));
Viper_Sb
Really thanks. It works with some changes!!!
Alexander.Plutov