我试图通过删除permission
值为no
的子数组来过滤多维数组。
我的阵列:
$array = array(
array(
'name' => 'dashboard',
'permission' => 'yes'
),
array(
'name' => 'Purchase Orders',
'permission' => 'yes',
'dropdown' => array(
array(
'name' => 'View Complete',
'permission' => 'yes'
),
array(
'name' => 'New PO',
'permission' => 'no'
)
)
),
array(
'name' => 'dashboard',
'permission' => 'no'
)
);
这是我想要的结果:(注意permission=>'no'
的所有群组已被完全移除)
$array = array(
array(
'name' => 'dashboard',
'permission' => 'yes'
),
array(
'name' => 'Purchase Orders',
'permission' => 'yes',
'dropdown' => array(
array(
'name' => 'View Complete',
'permission' => 'yes'
)
)
)
);
将array_filter()
与回调函数一起使用非常简单地在第一级进行,但我无法在每个级别上找到一个简单的解决方案。
目前我的解决方案是循环并取消设置每个键,但它需要知道数组的确切结构并且感觉非常混乱。
答案 0 :(得分:1)
foreach($array as $key => $item) {
if(isset($item['permission']) && $item['permission'] == 'no') {
unset($array[$key]);
}
if(isset($item['dropdown'])) {
foreach($item['dropdown'] as $key2 => $item2) {
if(isset($item2['permission']) && $item2['permission'] == 'no') {
unset($array[$key]['dropdown'][$key2]);
}
}
}
}
答案 1 :(得分:1)
这是一个带递归的方法。一些内联评论有助于解释,但没有太多可解释的基本功能本身并不表达。
代码:(Demo)
$array = array(
array(
'name' => 'dashboard',
'permission' => 'yes'
),
array(
'name' => 'Purchase Orders',
'permission' => 'yes',
'dropdown' => array(
array(
'name' => 'View Complete',
'permission' => 'yes'
),
array(
'name' => 'New PO',
'permission' => 'no'
)
)
),
array(
'name' => 'dashboard',
'permission' => 'no'
));
function recursive_filter($array){
foreach($array as $k=>&$subarray){ // make modifiable by reference
if(isset($subarray['permission']) && $subarray['permission']=='no'){ // check that this element exists before trying to access it
unset($array[$k]); // remove subarray
}elseif(isset($subarray['dropdown'])){ // check that this element exists before trying to access it
$subarray['dropdown']=recursive_filter($subarray['dropdown']); // recurse
}
}
return $array;
}
var_export(recursive_filter($array));
输出:
array (
0 =>
array (
'name' => 'dashboard',
'permission' => 'yes',
),
1 =>
array (
'name' => 'Purchase Orders',
'permission' => 'yes',
'dropdown' =>
array (
0 =>
array (
'name' => 'View Complete',
'permission' => 'yes',
),
),
),
)