gpt4 book ai didi

php - 获取每一行的递归深度

转载 作者:可可西里 更新时间:2023-11-01 07:37:58 25 4
gpt4 key购买 nike

我有以下数据库表

enter image description here

82 是 84 的父级。24 是 82 和 83 的父级。在 php 中,我有一个通过 uid 获取行的方法。

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

这将从表中检索第 7 个和第 6 个值。现在我不仅要获取 uid 相等的行,还要获取父项是 uid 的子项的行。例如。 82 是 84 的 parent ,也是 24 的 child 。

所以我想到了一些递归。

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 深度存储在 $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
)
)

关于php - 获取每一行的递归深度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6383952/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com