PHP - 查找数组父键 [英] PHP - Find parent key of array
本文介绍了PHP - 查找数组父键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图找到一种方法返回一个数组的父键的值。
例如,从阵列下面我想找出母公司的关键,其中$数组['身份证'] ==0002。
父关键是显而易见的,因为它是这里定义(这将是产品),但通常它会是动态的,因此这个问题。在'ID'和'身份证'的价值,虽然已知的。
[0] =>排列
(
[数据] =>
[ID] => 0000
[名] =>漩涡
[类别] =>排列
(
[0] =>排列
(
[ID] => 0001
[名] =>旋转
[产品] =>排列
(
[0] =>排列
(
[ID] => 0002
[文件名] => 1.JPG
)
[1] =>排列
(
[ID] => 0003
[文件名] => 2.JPG
)
)
)
)
)
解决方案
一个有点粗糙递归,但它应该工作:
函数find_parent($数组,$针,$父= NULL){
的foreach($数组$关键=> $值){
如果(is_array($值)){
$传球= $父母;
如果(IS_STRING($键)){
$传球= $关键;
}
$发现= find_parent(价值$,$针,$通行证);
如果($找到了!== FALSE){
返回$找到;
}
}否则如果($关键==='ID'和;&安培; $值$ ===针){
返回$父母;
}
} 返回false;
}$ parentkey = find_parent($阵列,'0002');
I'm trying to find a way to return the value of an array's parent key.
For example, from the array below I'd like to find out the parent's key where $array['id'] == "0002". The parent key is obvious because it's defined here (it would be 'products'), but normally it'd be dynamic, hence the problem. The 'id' and value of 'id' is known though.
[0] => Array
(
[data] =>
[id] => 0000
[name] => Swirl
[categories] => Array
(
[0] => Array
(
[id] => 0001
[name] => Whirl
[products] => Array
(
[0] => Array
(
[id] => 0002
[filename] => 1.jpg
)
[1] => Array
(
[id] => 0003
[filename] => 2.jpg
)
)
)
)
)
解决方案
A little crude recursion, but it should work:
function find_parent($array, $needle, $parent = null) {
foreach ($array as $key => $value) {
if (is_array($value)) {
$pass = $parent;
if (is_string($key)) {
$pass = $key;
}
$found = find_parent($value, $needle, $pass);
if ($found !== false) {
return $found;
}
} else if ($key === 'id' && $value === $needle) {
return $parent;
}
}
return false;
}
$parentkey = find_parent($array, '0002');
这篇关于PHP - 查找数组父键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文