获得特定元素的深度以阵列 [英] Getting the depth of a specific element in an array
本文介绍了获得特定元素的深度以阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
下面是一个数组/树我有一个例子。我如何才能找到的深度,例如, 2788
(答案应该是3)?
阵列
(
[2773] =>排列
(
[POST_ID] => 2773
[儿童] =>排列
(
[2777] =>排列
(
[POST_ID] => 2777
[儿童] =>排列
(
[2788] =>排列
(
[POST_ID] => 2788
[儿童] =>排列
(
)
)
)
)
)
)
)
解决方案
这得到深度,不是期望的子键的值:
函数getDepth($键,$数组$ CURDEPTH = 0){
如果(in_array($键,array_keys($阵列))){
返回1 + $ CURDEPTH;
}其他{
的foreach($数组作为$子阵){
$ R = getDepth($键,$子阵['孩子'],$ CURDEPTH + 1);
如果($ R&0)返回$ R;
}
}
返回0;
}
如果没有找到匹配,函数返回 0
。
功能进行了测试,并与您的示例如下:
$阵列=阵列(
2773 =>排列
(
POST_ID'=> 2773,
'孩子'=>排列
(
2777 =>排列
(
POST_ID'=> 2777,
'孩子'=>排列
(
2788 =>排列
(
POST_ID'=> 2788,
'孩子'=>排列
(
)
)
)
)
)
)
);回声getDepth(2788,$阵列); //返回3
Below is an example of an array/tree I have. How would I find the depth of, for example, 2788
(the answer should be 3)?
Array
(
[2773] => Array
(
[post_id] => 2773
[children] => Array
(
[2777] => Array
(
[post_id] => 2777
[children] => Array
(
[2788] => Array
(
[post_id] => 2788
[children] => Array
(
)
)
)
)
)
)
)
解决方案
This gets the depth, not the values of the desired child key:
function getDepth($key, $array, $curDepth = 0) {
if (in_array($key, array_keys($array))) {
return 1 + $curDepth;
} else {
foreach ($array as $subArray) {
$r = getDepth($key, $subArray['children'], $curDepth + 1);
if ($r > 0) return $r;
}
}
return 0;
}
If no match is found, the function returns 0
.
Function has been tested and works with your example:
$array = array(
2773 => Array
(
'post_id' => 2773,
'children' => Array
(
2777 => Array
(
'post_id' => 2777,
'children' => Array
(
2788 => Array
(
'post_id' => 2788,
'children' => Array
(
)
)
)
)
)
)
);
echo getDepth(2788, $array); // Returns 3
这篇关于获得特定元素的深度以阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文