unset объект внутри массива объектов

У меня проблема с удалением элементов из массива с объектом, тот же код запускается в другом приложении. После цикла массив $categories должен быть пуст. Приведенный ниже код удаляет все дочерние категории, а затем удаляет родительскую категорию, если пользователь передает второй параметр как TRUE, если у родителя нет дочернего элемента, удалите только его.

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

person owis sabry    schedule 08.08.2016    source источник


Ответы (1)


Для удаления/установки нулевого элемента массива нам нужно передать этот конкретный индекс массива unset($children[$key]);-

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

Надеюсь, что это поможет вам.

person Afshan Shujat    schedule 08.08.2016