取消数组对象中的一个对象

3

我有一个关于从包含对象的数组中删除项的问题,相同的代码在其他应用程序中运行良好。在循环数组 $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;
    }
}
1个回答

0

如果要删除/设置数组元素为空,我们需要传递该数组索引的特定位置 unset($children[$key]);-

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

希望这能对你有所帮助。

unset函数适用于对象、变量和数组。它完全不依赖索引。为了确保,我测试了你的代码,结果如预期一样出现了错误。感谢你的尝试。请查看PHP参考手册http://php.net/manual/en/function.unset.php。 - owis sabry
哦,抱歉有个打字错误,你需要写成unset($children[$key]);。 - Afshan Shujat
如果要取消数组中的特定元素,您需要传递要取消的特定值索引。 - Afshan Shujat
你的代码错误在于"$children as $key->$child",我使用的是面向对象而不是数组,错误是“未定义变量:child”。 - owis sabry
请尝试使用 $children as $key=>$child。 - Afshan Shujat

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接