2011-06-17 95 views
4

我有以下分貝表獲取遞歸深度的每一行

enter image description here

82是84 24母體是82和83母體在PHP我具有由讀取行的方法UID。

public function fetchByUid($uid){ 
    //code 
} 

這將檢索表中的第7和第6個值。現在我不僅要獲取uid相等的行,還要獲取其父母是uid子項的行。例如。 82是84的父親,但也是24的孩子。

所以我想出了一些遞歸。

public function fetchByUidRec($uid, $data, $counter){ 
    //set of rows by uid 
    $db_resultSet; 

    foreach($db_resultSet as $row){ 
     $entry = array(); 
     $entry['id'] = $row->id; 
     $entry['uid'] = $row->uid; 
     $entry['rid'] = $row->rid; 
     $entry['layer'] = $counter; 
     $data [] = $entry; 

     //now I want to do the same on the child 
     $data [] = fetchByUidRec($row->rid, $data, $counter = $counter + 1) 
    } 

    return $data; 
} 

public function getchByUid($uid){ 
    $data = array(); 
    $counter = 0; 

    return fetchByUidRec($uid, $data, $counter) 
} 

但是,這並不在所有的工作:(我想存儲在$數據當前recrusion深度[「層」]

任何想法

回答

2

如果我理解正確你:

$rows = array 
(
    0 => array('id' => 8, 'uid' => 82, 'rid' => 84), 
    1 => array('id' => 7, 'uid' => 24, 'rid' => 82), 
    2 => array('id' => 6, 'uid' => 24, 'rid' => 83), 
); 

function fetchByUidRec($uid, $counter = 0) 
{ 
    global $rows; 

    // or in your case 
    // $rows = SELECT FROM table WHERE uid = $uid; 

    $data = array(); 

    foreach ($rows as $row) 
    { 
     if ($row['uid'] == $uid) 
     { 
      $data[] = array_merge($row, array('layer' => $counter)); 
      $data = array_merge($data, fetchByUidRec($row['rid'], $counter++)); 
     } 
    } 

    return $data; 
} 

echo '<pre>'; 
print_r(fetchByUidRec(24)); 
echo '</pre>'; 

輸出

Array 
(
    [0] => Array 
     (
      [id] => 7 
      [uid] => 24 
      [rid] => 82 
      [layer] => 0 
     ) 

    [1] => Array 
     (
      [id] => 8 
      [uid] => 82 
      [rid] => 84 
      [layer] => 0 
     ) 

    [2] => Array 
     (
      [id] => 6 
      [uid] => 24 
      [rid] => 83 
      [layer] => 1 
     ) 
) 
+0

感謝,但你可以在我的代碼見我不從表中檢索整個行,但只有那些符合UID的是,這是由指示$ db_resultSet ....;對於父母的每個孩子,我現在再次爲uid的所有孩子進行db查詢(這將是第1層),等等...... – 2011-06-17 10:30:35

+0

@ArtWorkAD:這與您的問題無關,我想,我只是調整了您的代碼以提供一個完全可行的例子。我建議你修正你的代碼中的錯別字和錯誤,也許還提供'fetchByUid' /'getchByUid'方法的代碼。你的問題有點混亂。 – 2011-06-17 10:37:48

+0

@ArtWorkAD:在我的代碼中查看評論,難道不是嗎? – 2011-06-17 10:43:46