从树构建数组的递归函数
我有一个看起来像这样的数组:
Array (
[0] => Array
(
[term_id] => 23
[name] => testasdf
[depth] => 1
)
[1] => Array
(
[term_id] => 26
[name] => asdf
[depth] => 2
)
[2] => Array
(
[term_id] => 31
[name] => Another level deep
[depth] => 3
)
[3] => Array
(
[term_id] => 32
[name] => Another level deep
[depth] => 2
)
[4] => Array
(
[term_id] => 24
[name] => testasdf
[depth] => 1
)
[5] => Array
(
[term_id] => 27
[name] => asdf
[depth] => 1
)
)
这是我正在使用的递归函数,它可以工作,除了在某些情况下(看起来深度更大。
function process(&$arr, &$prev_sub = null, $cur_depth = 1) {
$cur_sub = array();
while($line = current($arr)){
if($line['depth'] < $cur_depth){
return $cur_sub;
}elseif($line['depth'] > $cur_depth){
$prev_sub = $this->process($arr, $cur_sub, $cur_depth + 1 );
}else{
$cur_sub[$line['term_id']] = array('term_id' => $line['term_id'], 'name' => $line['name']);
$prev_sub =& $cur_sub[$line['term_id']];
next($arr);
}
}
return $cur_sub;
}
这就是结果的样子:
Array
(
[23] => Array
(
[26] => Array
(
[31] => Array
(
[term_id] => 31
[name] => Another level deep
)
)
[32] => Array
(
[term_id] => 32
[name] => Another level deep
)
)
[24] => Array
(
[term_id] => 24
[name] => testasdf
)
[27] => Array
(
[term_id] => 27
[name] => asdf
)
)
知道我如何才能拥有它吗?所有深度都显示 term_id 和名称?
I have an array that looks like this:
Array (
[0] => Array
(
[term_id] => 23
[name] => testasdf
[depth] => 1
)
[1] => Array
(
[term_id] => 26
[name] => asdf
[depth] => 2
)
[2] => Array
(
[term_id] => 31
[name] => Another level deep
[depth] => 3
)
[3] => Array
(
[term_id] => 32
[name] => Another level deep
[depth] => 2
)
[4] => Array
(
[term_id] => 24
[name] => testasdf
[depth] => 1
)
[5] => Array
(
[term_id] => 27
[name] => asdf
[depth] => 1
)
)
Here is the recursive function that I'm using, it works except in some cases (where the depth is greater it seems.
function process(&$arr, &$prev_sub = null, $cur_depth = 1) {
$cur_sub = array();
while($line = current($arr)){
if($line['depth'] < $cur_depth){
return $cur_sub;
}elseif($line['depth'] > $cur_depth){
$prev_sub = $this->process($arr, $cur_sub, $cur_depth + 1 );
}else{
$cur_sub[$line['term_id']] = array('term_id' => $line['term_id'], 'name' => $line['name']);
$prev_sub =& $cur_sub[$line['term_id']];
next($arr);
}
}
return $cur_sub;
}
This is how the results look:
Array
(
[23] => Array
(
[26] => Array
(
[31] => Array
(
[term_id] => 31
[name] => Another level deep
)
)
[32] => Array
(
[term_id] => 32
[name] => Another level deep
)
)
[24] => Array
(
[term_id] => 24
[name] => testasdf
)
[27] => Array
(
[term_id] => 27
[name] => asdf
)
)
Any idea how I can have it so the term_id and name is shown for all depths?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
试试这个:
try this: