php + mysql to achieve unlimited classification
<pre>
the above mentioned id pid path name
1 computer 00
2 mobile phone 00
3 notebook 10-1
This 30-1-3 4 Super
This game 0-1-3 5. 3
</ pre>
In this way, suppose we want to query all descendants of classification under the computer, only a sql statement:
<pre>
select id,name from category where path like ( select concat(path,'-',id,'%') path from category where id=1 );
</pre>
Advantages: easy query, efficient, path fields can be indexed.
Cons: Updates node relationship trouble, you need to update all the younger generation path field.
A program sample code:
<pre>
<?php
$addrs = array(
array('id'=>1, 'name'=>'中国', 'pid'=>0),
array('id'=>2, 'name'=>'河南', 'pid'=>1),
array ( 'id' => 3, 'name' => 'Zhengzhou', 'pid' => 2),
array ( 'id' => 4, 'name' => 'Luoyang', 'pid' => 2),
array ( 'id' => 5, 'name' => 'Anyang', 'pid' => 2),
array('id'=>6, 'name'=>'林州', 'pid'=>5),
array ( 'id' => 7, 'name' => 'Anyang County', 'pid' => 5),
array('id'=>8, 'name'=>'内黄', 'pid'=>5),
array ( 'id' => 9, 'name' => 'HuaXian', 'pid' => 5),
array ( 'id' => 10, 'name' => 'Jiaoxiang', 'pid' => 6),
array('id'=>11, 'name'=>'湖南', 'pid'=>1),
array('id'=>12, 'name'=>'长沙', 'pid'=>11),
array('id'=>13, 'name'=>'湘潭', 'pid'=>11),
array ( 'id' => 14, 'name' => 'Yuelu', 'pid' => 12),
);
// query sub-tree (recursive method)
function get_childs($id)
{
global $addrs;
$ret = array();
foreach ($ addrs as & $ addr) // used herein & operator, to improve efficiency
{
if($addr['pid'] == $id)
{
$addr['children'] = get_childs($addr['id']);
Right $ [] = $ addr;
}
}
return $ right;
}
// test code
echo '<pre>';
print_r( get_childs(1) );
echo '<hr/>';
print_r($addrs);
</pre>