PHP递归取消设置数组键,如果匹配 [英] PHP Recursively unset array keys if match
本文介绍了PHP递归取消设置数组键,如果匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下的数组,我需要通过递归循环,并删除有钥匙'字段的任何儿童阵列。我曾尝试阵列过滤器,但我有麻烦它的任何工作。
$ myArray的=阵列(
'项目'=>阵列(
'域'=>阵列('身份证','名'),
部分= GT;阵列(
'域'=>阵列('PART_NUMBER','part_name')
)
)
'所有者'=>阵列(
'域'=>阵列('身份证','名','积极'),
本公司=>阵列(
'域'=>阵列('身份证','名',),
'位置'= GT;阵列(
'域'=>阵列('身份证','名','地址','拉链'),
国家= GT;阵列(
'域'=>阵列('身份证','名')
)
)
)
)
);
这是我需要的结果是这样的:
$ myArray的=阵列(
'项目'=>阵列(
部分= GT;阵列(
)
)
'所有者'=>阵列(
本公司=>阵列(
'位置'= GT;阵列(
国家= GT;阵列(
)
)
)
)
);
解决方案
如果你想递归操作,你需要传递数组作为的参考,否则你做不必要的复制了很多:
函数recursive_unset(安培; $数组$ unwanted_key){
未设置($数组[$ unwanted_key]);
的foreach($数组和放大器; $值){
如果(is_array($值)){
recursive_unset(价值$,$ unwanted_key);
}
}
}
I have the following array that I need to recursively loop through and remove any child arrays that have the key 'fields'. I have tried array filter but I am having trouble getting any of it to work.
$myarray = array(
'Item' => array(
'fields' => array('id', 'name'),
'Part' => array(
'fields' => array('part_number', 'part_name')
)
),
'Owner' => array(
'fields' => array('id', 'name', 'active'),
'Company' => array(
'fields' => array('id', 'name',),
'Locations' => array(
'fields' => array('id', 'name', 'address', 'zip'),
'State' => array(
'fields' => array('id', 'name')
)
)
)
)
);
This is how I need it the result to look like:
$myarray = array(
'Item' => array(
'Part' => array(
)
),
'Owner' => array(
'Company' => array(
'Locations' => array(
'State' => array(
)
)
)
)
);
解决方案
If you want to operate recursively, you need to pass the array as a reference, otherwise you do a lot of unnecessarily copying:
function recursive_unset(&$array, $unwanted_key) {
unset($array[$unwanted_key]);
foreach ($array as &$value) {
if (is_array($value)) {
recursive_unset($value, $unwanted_key);
}
}
}
这篇关于PHP递归取消设置数组键,如果匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文