2015-10-13 93 views
-2
$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() 
       ) 
     ); 

我的要求:数组PHP。如何获得深元素的数组

做一个功能在$莽阵列深项目的数量。

样品。 深任何项目将返回样子的:

  • 'UID'= 10将返回深= 3

  • 'UID'= 11将返回深= 4

  • “UID '= 8将返回深= 2

  • 为 'uid'= 2将返回深= 1

样的功能看起来像

function count_deep($array,$uid){ return $deep; }

请人帮助我。非常感谢。

+0

如果你能告诉我们,会有什么帮助。你想如何查询你的巨型数组,以及你想从查询中返回什么? – castis

+0

'function count_deep($ array,$ uid){ return $ deep; }' –

+0

如果是学校任务,并且数组不是那么深的递归函数和深度数就可以完成几乎没有代码的工作。 您的count_deep可以调用count_deep_rec($ array,$ uid,0/*初始深度* /,false/* is_found?*) 找到可用于稍后停止其他递归调用,如果存在并改进perf。 –

回答

1

您可以使用以下递归函数来获取找到uuid值的深度。如果完全没有找到uuid值,则此版本返回值0。

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和阵列

$depth = searchDepth(10, $mang); 
+0

非常感谢。是工作。 –

0

有人做过already asked this功能。在那里寻找最佳答案;但是,请注意,在PHP中可能有一个无限深的数组,因此为了万一事情变得荒谬可以使用最大深度是个好主意。

+0

谢谢,我发现这个,但它不帮助我。 –