【问题标题】:unset object inside an array of objects在对象数组中取消设置对象
【发布时间】:2016-12-14 01:42:42
【问题描述】:

我在使用对象从数组中删除项目时遇到问题,相同的代码在其他应用程序中运行。循环后数组$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;
    }
}

【问题讨论】:

    标签: php arrays oop codeigniter-3 unset


    【解决方案1】:

    要删除/设置 null 数组元素,我们需要传递数组的特定索引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参考php.net/manual/en/function.unset.php
    • 哦抱歉有一个错字你需要写 unset($children[$key]);
    • 如果要取消设置特定数组元素的数组,您需要传递要取消设置的特定值索引。
    • 代码的错误在这里“$children as $key->$child”,我使用的是 oop 而不是数组,错误是“未定义的变量:子”
    • $children as $key=>$child,请试试这个。
    猜你喜欢
    • 2020-12-15
    • 1970-01-01
    • 2017-05-05
    • 2015-09-11
    • 2021-05-02
    • 1970-01-01
    • 1970-01-01
    • 2018-02-23
    • 2016-03-25
    相关资源
    最近更新 更多