3

I have a problem with remove items from an array with object, the same code run in other app. After looping the array $categories should be empty. The code bellow removes all children categories then removes the parent category if the user pass the second parameter as TRUE, if the parent doesn't have a child then remove it only.

//the $id of the category to be removed 
// $remove_children is state if you accept removing children categories  
function remove_category($id = null, $remove_children = false) {
    if ($this->MD->is_category($id) && is_bool($remove_children)) {
        //get all children category
        $children = $this->get_children_categories($id);
        if (!$children) {
            return $this->MD->remove($id, $this->categories_table);
        } else {
            if ($remove_children && is_array($children)) {
                unset($children['parent_category']);
                foreach ($children as $child) {
                    $removed = $this->MD->remove($child->id, $this->categories_table);
                    if ($removed) {
                        //problem here
                        unset($child);
                    }
                }
                //the $children is not empty after remove all the items
                if (empty($children)) {
                    return $this->MD->remove($id, $this->categories_table);
                } else {
                    return false;
                }
            } else {
                return false;
            }
        }
    } else {
        return false;
    }
}
Elzo Valugi
  • 27,240
  • 15
  • 95
  • 114
owis sabry
  • 154
  • 9

1 Answers1

0

For removing/setting null an array element we need to pass that particular index of array unset($children[$key]);-

foreach ($children as $key=>$child) {
                    $removed = $this->MD->remove($child->id, $this->categories_table);
                    if ($removed) {
                        //problem here
                        unset($children[$key]);
                    }
                }

Hope this will help you.

Afshan Shujat
  • 541
  • 4
  • 9
  • unset function works with object ,variables and array . It's not depending on indexes at all. for make sure i test your code and it's end with error as expected . $thanks for the try. Take a look to php reference http://php.net/manual/en/function.unset.php – owis sabry Aug 08 '16 at 10:43
  • oh sorry there is a typo mistake you need to write unset($children[$key]); – Afshan Shujat Aug 08 '16 at 10:45
  • In case of array for unsetting particular array element you need to pass that particular value index that you want to unset. – Afshan Shujat Aug 08 '16 at 10:47
  • the error of your code is here "$children as $key->$child", i'm using oop not an array and the error is "Undefined variable: child" – owis sabry Aug 08 '16 at 10:48
  • $children as $key=>$child, try this plz. – Afshan Shujat Aug 08 '16 at 10:51