2015-10-13 95 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

謝謝,我發現這個,但它不幫助我。 –