21,886
社区成员
发帖
与我相关
我的任务
分享
mysql_connect();
//测试数据
$sql =<<< SQL
select * from (
select '1' as id, '0' as pid, 'Food' as title
union all select '2', '1', 'Fruit'
union all select '3', '2', 'Red'
union all select '4', '3', 'Cherry'
union all select '5', '2', 'Yellow'
union all select '6', '5', 'Banana'
union all select '7', '1', 'Meat'
union all select '8', '7', 'Beef'
union all select '9', '7', 'Pork'
) t
order by pid, id
SQL;
$rs = mysql_query($sql);
$res = array(); //结果数组
$ind = array(); //索引数组
while($row = mysql_fetch_assoc($rs)) {
list($id, $pid) = array_values($row);
$ind[$id] = $row;
if(isset($ind[$pid])) $ind[$pid]['child'][$id] =& $ind[$id]; //构造索引
if($pid == 0) $res[$id] =& $ind[$id]; //转存根节点组
}
echo '<xmp>' . print_r($res, 1);
Array
$arr = array(
array(
'id'=>10,
'pid'=>13,
),
array(
'id'=>11,
'pid'=>13,
),
array(
'id'=>12,
'pid'=>14,
),
array(
'id'=>13,
'pid'=>14,
),
array(
'id'=>14,
'pid'=>0,
),
);
实际值肯定不是那样的。
这种方法必须要严格按照 父数据在子数据之前 的格式。
解决办法思考ing。。。