2011-01-27 84 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