Heim  >  Artikel  >  Backend-Entwicklung  >  读取树状数据的步骤

读取树状数据的步骤

WBOY
WBOYOriginal
2016-06-13 12:54:031151Durchsuche

读取树状数据的方法
读取树状数据的方法
一般在读取用“邻接列表算法”组织的数据时,需要使用递归逐层读取
或者读取数据到数组,然后用递归或非递归的方法再行处理
这里介绍一种边读边生成“树状”数组的方法,希望对你有用

mysql_connect();<br />
<br />
//测试数据<br />
$sql =<<< SQL<br />
select * from (<br />
  select '1' as id, '0' as pid, 'Food' as title<br />
  union all select '2', '1', 'Fruit'<br />
  union all select '3', '2', 'Red'<br />
  union all select '4', '3', 'Cherry'<br />
  union all select '5', '2', 'Yellow'<br />
  union all select '6', '5', 'Banana'<br />
  union all select '7', '1', 'Meat'<br />
  union all select '8', '7', 'Beef'<br />
  union all select '9', '7', 'Pork'<br />
  ) t<br />
  order by pid, id<br />
SQL;<br />
<br />
$rs = mysql_query($sql);<br />
<br />
$res = array(); //结果数组<br />
$ind = array(); //索引数组<br />
while($row = mysql_fetch_assoc($rs)) {<br />
  list($id, $pid) = array_values($row); <br />
  $ind[$id] = $row;<br />
  if(isset($ind[$pid])) $ind[$pid]['child'][$id] =& $ind[$id]; //构造索引<br />
  if($pid == 0) $res[$id] =& $ind[$id]; //转存根节点组<br />
}<br />
<br />
echo '<xmp>' . print_r($res, 1);<br />
Array
(
    [1] => Array
        (
            [id] => 1
            [pid] => 0
            [title] => Food
            [child] => Array
                (
                    [2] => Array
                        (
                            [id] => 2
                            [pid] => 1
                            [title] => Fruit
                            [child] => Array
                                (
                                    [3] => Array
                                        (

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Vorheriger Artikel: 深夜发帖,有些灵异 Nächster Artikel: php资料引入和C++的不同