我有一个数组数组,
我已经发布了下面的基本结构, 递归可以是任何深度。
无论如何,我想要做的是,遍历数组中的每个项目,如果它的['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()
)
)
)
)
)
);
答案 0 :(得分:0)
您可以在顶部数组上使用array_filter
,然后在回调函数中分析每个子数组。看看http://www.php.net/manual/en/function.array-filter.php
答案 1 :(得分: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);
答案 2 :(得分:0)
您可以使用array_map或array_filter来遍历每个孩子并取消设置所需的孩子。