用 list 处置树状数据(邻接列表)

WBOY
Release: 2016-06-13 12:34:02
Original
967 people have browsed it

用 list 处理树状数据(邻接列表)
现有一个数组

$d = array(<br />
  array( '公告', 1, 0 ),<br />
  array( '文章', 2, 0 ),<br />
  array( '文章1', 3, 2 ),<br />
  array( '文章2', 4, 2),<br />
  array( '文章1评论', 5, 3 ),<br />
  array( '文章2评论', 6, 4 ),<br />
  array( '文章1评论1', 7, 3 ),<br />
  array( '文章1评论评论', 8, 5 ),<br />
);<br />
Copy after login
期望如下输出
公告<br />
文章<br />
  文章1<br />
    文章1评论<br />
      文章1评论评论<br />
    文章1评论1<br />
  文章2<br />
    文章2评论<br />
Copy after login

于是可以
foreach($d as $t) list($a[$pid][$id], $id, $pid) = $t;<br />
Copy after login
得到
Array<br />
(<br />
    [0] => Array<br />
        (<br />
            [1] => 公告<br />
            [2] => 文章<br />
        )<br />
<br />
    [2] => Array<br />
        (<br />
            [3] => 文章1<br />
            [4] => 文章2<br />
        )<br />
<br />
    [3] => Array<br />
        (<br />
            [5] => 文章1评论<br />
            [7] => 文章1评论1<br />
        )<br />
<br />
    [4] => Array<br />
        (<br />
            [6] => 文章2评论<br />
        )<br />
<br />
    [5] => Array<br />
        (<br />
            [8] => 文章1评论评论<br />
        )<br />
<br />
)<br />
Copy after login
可以看到,数据按第3列聚类了
于是再用一个递归函数就可实现数据的展示了
function foo($ar, $pid=0, $deep=0) {<br />
  foreach($ar[$pid] as $k=>$v) {<br />
    printf("%s%s\n", str_repeat(' ', $deep), $v);<br />
    if(isset($ar[$k])) foo($ar, $k, $deep+2);<br />
  }<br />
}<br />
Copy after login
调用 foo($a);

php list
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!