开发者

Get recursive depth for every row

开发者 https://www.devze.com 2023-03-13 11:39 出处:网络
I have the follo开发者_如何学Cwing db table 82 is the parent of 84. 24 is the parent of 82 and 83. In php I have a method to fetch rows by uid.

I have the follo开发者_如何学Cwing db table

Get recursive depth for every row

82 is the parent of 84. 24 is the parent of 82 and 83. In php I have a method to fetch rows by uid.

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

This would retrieve the 7th and 6th value from the table. Now I want to fetch not only the rows where uid is equal but also the rows where the parent is the child of uid. E.g. 82 is a parent of 84 but also a child of 24.

So I came up with some recursion.

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

But that does not work at all :( I want to store the current recrusion depth in $data['layer']

Any ideas?


If I understood you correctly:

$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;
}

Example:

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

Output:

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

精彩评论

暂无评论...
验证码 换一张
取 消