阵列PHP。如何获得深数组元素的 [英] Array PHP. How to get deep of element in array
问题描述
$mang = array(
'0' => array(
'uid' => 2,
'introducer_uid' => 1,
'introducer_users' => array(
'0' => array(
'uid' => 8,
'introducer_uid' => 2,
'introducer_users' => array()
),
'1' => array(
'uid' => 9,
'introducer_uid' => 2,
'introducer_users' => array())
)
),
'1' => array(
'uid' => 3,
'introducer_uid' => 1,
'introducer_users' => array(
'0' => array(
'uid' => 5,
'introducer_uid' => 3,
'introducer_users' => array()
),
'1' => array(
'uid' => 6,
'introducer_uid' => 3,
'introducer_users' => array()
),
'2' => array(
'uid' => 7,
'introducer_uid' => 3,
'introducer_users' => array(
'0' => array(
'uid' => 10,
'introducer_uid' => 7,
'introducer_users' => array(
'0' => array(
'uid' => 11,
'introducer_uid' => 10,
'introducer_users' => array()
)
)
)
)
)
)
),
'2' => array(
'uid' => 4,
'introducer_uid' => 1,
'introducer_users' => array()
)
);
我的要求:
请一个函数来计数在$芒阵深项目。
Make a functions to Count deep of item in $mang array.
样品。
深任何项目将返回如下:
Sample. Deep of any item will return look like:
-
为'uid = 10将返回深= 3
'uid' = 10 will return deep = 3
为'uid = 11将返回深= 4
'uid' = 11 will return deep = 4
为'uid = 8将返回深= 2
'uid' = 8 will return deep = 2
为'uid = 2将返回深= 1
'uid' = 2 will return deep = 1
样的功能看起来像
函数count_deep($数组$ UID){$返回深; }
请人帮助我。谢谢你这么多。
Anyone please help me. Thank you so much.
推荐答案
您可以使用下面的递归函数来获得的深度的其中UUID值被找到。如果UUID值没有发现在所有的这个版本将返回值0。
You can use the following recursive function to get the depth where the uuid value is found. This version returns value 0 if the uuid value is not found at all.
function searchDepth($uid, $array, $depth = 0)
{
$depth++;
foreach ($array as $element)
{
if (isset($element['uid']) && $element['uid'] == $uid)
{
return $depth;
}
else if (isset($element['introducer_users']))
{
$result = searchDepth($uid, $element['introducer_users'], $depth);
if ($result != 0)
{
return $result;
}
}
}
return 0;
}
和与搜索UUID和数组调用该函数
And to invoke the function with the search uuid and the array
$depth = searchDepth(10, $mang);
这篇关于阵列PHP。如何获得深数组元素的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!