function list_to_tree($list,$root=0,$pk='cid',$pid = 'pid',$child = '_child'){if(is_array($list)) {
// 创建基于主键的数组引用
foreach ($list as $key => $data) {
$refer[$data[$pk]] =& $list[$key];
}
foreach ($list as $key => $data) {
// 判断是否存在parent
$parentId = $data[$pid];
if ($root == $parentId) {
$tree[$list[$key][$pk]] =& $list[$key];
}else{
if (isset($refer[$parentId])) {
$parent =& $refer[$parentId];
$parent[$child][$list[$key][$pk]] =& $list[$key];
}
}
}
}
return $tree;
}
//链接数据库
$con = mysql_connect("localhost", "root", "123456");
if (!$con){
die('Could not connect: ' . mysql_error());
}
//选择数据库
$db_selected = mysql_select_db("newasf04",$con);
//设置数据库编码
mysql_query("set names 'utf8'");
//sql语句
$sql = "SELECT cid,pid,name from asf_mall_category";
//执行sql语句
$result = mysql_query($sql);
//把查询结果放到一个数组中
while ($row=mysql_fetch_assoc($result)){
$arr[]=$row;
}
// 释放资源
mysql_free_result($result);
// 关闭连接
mysql_close();
$newarr=list_to_tree($arr);
print_r($newarr);