0

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.

2 Answers 2

1

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));
Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.