2011-01-27 82 views
3

讓我們假設我有以下嵌套/多維數組:如何從給定子鍵查找數組的所有父鍵?

array(
    'World'=>array(
      'Asia'=>array(
       'Japan'=>array(
        'City'=>'Tokyo' 
       ) 
     ) 
    ) 
); 

我希望能夠找出所有的家長在當前城市的heriarchy。

例如,對於市,響應應該是包含父母的數組:

array(
    'World'=>array(
      'Asia'=>array(
       'Japan' 
     ) 
    ) 
); 

那麼,如何找到鏈中所有的家長嵌套數組中?

回答

4

遞歸是你的朋友在這裏。您需要遞歸遍歷數組並獲取所有父項。 Your problem is discussed here, take a look at this comment.

<?php 

function getParentStack($child, $stack) { 
    foreach ($stack as $k => $v) { 
     if (is_array($v)) { 
      // If the current element of the array is an array, recurse it and capture the return 
      $return = getParentStack($child, $v); 

      // If the return is an array, stack it and return it 
      if (is_array($return)) { 
       return array($k => $return); 
      } 
     } else { 
      // Since we are not on an array, compare directly 
      if ($v == $child) { 
       // And if we match, stack it and return it 
       return array($k => $child); 
      } 
     } 
    } 

    // Return false since there was nothing found 
    return false; 
} 

?> 
+0

你能提供一個如何做的例子嗎? – 2011-01-27 08:29:40