1

我有一个数组数组,

我在下面发布了基本结构,递归可以是任何深度。

无论如何,我想要做的是,遍历数组中的每个项目,如果它的['item']->data('id')值等于$id然后删除树的那个部分,

但我不确定最有效的方法是什么?

我认为这可能有效,但我错过了什么吗?

function removeKey($key, &$categories){
    foreach($categories as $k => $category){
        if($category['item']->data('id') == $key){
            unset($categories[$k]);
            return;
        }
        if(!empty($category['children']))
            removeKey($key, $category['children']);
    }
}

removeKey($id, $categories);

array(
    array(
        'item' => "category Object", //use ->data('id') to get the id!
        'children' => array(
            array(
                'item' => "category Object",
                'children' => array(
                    array(
                        'item' => "category Object",
                        'children' => array()
                    )
                )
            ),
            array(
                'item' => "category Object",
                'children' => array(
                    array(
                        'item' => "category Object",
                        'children' => array()
                    )
                )
            )
        )
    ),
    array(
        'item' => "category Object",
        'children' => array(
            array(
                'item' => "category Object",
                'children' => array(
                    array(
                        'item' => "category Object",
                        'children' => array()
                    )
                )
            ),
            array(
                'item' => "category Object",
                'children' => array(
                    array(
                        'item' => "category Object",
                        'children' => array()
                    )
                )
            )
        )
    )
);
4

3 回答 3

0

您可以使用array_maparray_filter遍历每个孩子并取消设置所需的孩子。

于 2012-10-04T13:54:53.343 回答
0

您可以array_filter 在顶部数组上使用,然后在回调函数中分析每个子数组。看看http://www.php.net/manual/en/function.array-filter.php

于 2012-10-04T13:52:25.870 回答
0

尝试这个

function removeKey($key, &$categories){
    foreach($categories as $category){//y u were using $& 
        if($category['item']->data('id') == $key){
            unset($category);
            return;
        }
        if(!empty($category['children']))
            removeKey($key, $category['children']);
    }
}

removeKey($id, $categories);
于 2012-10-04T13:54:06.033 回答