php – 获取每行的递归深度

我有以下数据库表

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)
}

但这根本不起作用:(我想将当前的回弹深度存储在$data [‘layer’]中

有任何想法吗?

最佳答案 如果我理解正确的话:

$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
        )
)
点赞