2013-10-30 58 views
2

我的問題類似於Searching for an array key branch inside a larger array tree - PHP,但是對於不同的限制(比如正在處理等)以及爲什麼不爲了知識緣故,我只想用PHP實現它遞歸。PHP - 通過另一個多維數組搜索數組樹來獲取路徑

考慮一下這個數據:

array(
    'root_trrreeee1' => array(
     'path1' => array(
      'description' => 'etc', 
      'child_of_path_1' => array(
       array('name' => '1'), 
       array('name' => '1') 
      ) 
     ), 
     'path1' => array(
      'description' => 'etc', 
      'child_of_path_1' => array(
       array('name' => '1'), 
       array('name' => '1') 
      ) 
     ), 
    ), 
    'name' => '1', 
    1 => array('name' => '1'), 
    'another_leaf' => '1' 
) 

如果我搜索array('name' => '1')它應該返回我需要遍歷得到該值root_trrreeee1.path1.child_of_path_1.o路徑,最好返回數組:

array(
    0 => root_trrreeee1 
    1 => path1 
    2 => child_of_path_1 
    3 => 0 
) 

這是我試圖實現的遞歸函數,但它不工作:

function multidimensional_preserv_key_search($haystack, $needle, $path = array(), &$true_path = array()) 
{ 
    if (empty($needle) || empty($haystack)) { 
     return false; 
    } 

    foreach ($haystack as $key => $value) { 

     foreach ($needle as $skey => $svalue) { 

      if (is_array($value)) { 
       $path = multidimensional_preserv_key_search($value, $needle, array($key => $path), $true_path); 
      } 

      if (($value === $svalue) && ($key === $skey)) { 
       $true_path = $path; 
       return $true_path; 
      } 
     } 

    } 

    if (is_array($true_path)) { return array_reverse(flatten_keys($true_path)); } 
    return $path; 
} 


function flatten_keys($array) 
{ 
    $result = array(); 

    foreach($array as $key => $value) { 
     if(is_array($value)) { 
      $result[] = $key; 
      $result = array_merge($result, self::flatten_keys($value)); 
     } else { 
      $result[] = $key; 
     } 
    } 

    return $result; 
} 

它只返回一個空數組。 在此先感謝。

類似的問題,我發現:

+0

你有任何的解決方案。我被困在同一點 – dhpratik

+1

我實現了一個自定義的回溯算法:http://en.wikipedia.org/wiki/Backtracking(頁面上的代碼) – eagleal

回答