来自二维 php 的分层二维 php 数组
hierarchial two dimetional php array from an two dimetional php
我有一个包含所有用户的多维数组,如下所示。
Array
(
[0] => Array
(
[username] => santoshe62
[sponsor] => santoshe61
)
[1] => Array
(
[username] => santoshe63
[sponsor] => santoshe62
)
[2] => Array
(
[username] => santoshe65
[sponsor] => santoshe64
)
[3] => Array
(
[username] => santoshe67
[sponsor] => santoshe66
)
.............................
)
我想要此数组中的一个数组,其中包含给定用户的分层数据,如下所示。
Array
(
[0] => Array
(
[username] => santoshe62
[sponsor] => santoshe61
)
[1] => Array
(
[username] => santoshe63
[sponsor] => santoshe62
)
)
我试过了
function parseTree($datas, $parent = 0){
$tree = array();
for($i=0, $ni=count($datas); $i < $ni; $i++){
if($datas[$i]['sponsor'] == $parent){
$tree[] = $datas[$i];
parseTree($datas, $datas[$i]['username']);
}
}
return $tree;
}
任何人都可以帮助我找出我的代码中的错误吗?还请指点一下,我能不能直接从MySQLselect只有这个层级结构?现在我正在 select 从 DB 获取所有结果。
问题出在你的函数中,$tree = array();
。在每个递归函数调用中,这个 $tree
被初始化为一个空数组。您必须将其声明为 static
变量,以便它可以 仅初始化一次 并且可以在递归函数调用中保留其状态。
function parseTree($datas, $parent = 0){
static $tree = array();
...
}
我有一个包含所有用户的多维数组,如下所示。
Array
(
[0] => Array
(
[username] => santoshe62
[sponsor] => santoshe61
)
[1] => Array
(
[username] => santoshe63
[sponsor] => santoshe62
)
[2] => Array
(
[username] => santoshe65
[sponsor] => santoshe64
)
[3] => Array
(
[username] => santoshe67
[sponsor] => santoshe66
)
.............................
)
我想要此数组中的一个数组,其中包含给定用户的分层数据,如下所示。
Array
(
[0] => Array
(
[username] => santoshe62
[sponsor] => santoshe61
)
[1] => Array
(
[username] => santoshe63
[sponsor] => santoshe62
)
)
我试过了
function parseTree($datas, $parent = 0){
$tree = array();
for($i=0, $ni=count($datas); $i < $ni; $i++){
if($datas[$i]['sponsor'] == $parent){
$tree[] = $datas[$i];
parseTree($datas, $datas[$i]['username']);
}
}
return $tree;
}
任何人都可以帮助我找出我的代码中的错误吗?还请指点一下,我能不能直接从MySQLselect只有这个层级结构?现在我正在 select 从 DB 获取所有结果。
问题出在你的函数中,$tree = array();
。在每个递归函数调用中,这个 $tree
被初始化为一个空数组。您必须将其声明为 static
变量,以便它可以 仅初始化一次 并且可以在递归函数调用中保留其状态。
function parseTree($datas, $parent = 0){
static $tree = array();
...
}