|
首先數(shù)據(jù)庫(kù)字段為:
id ----------商品主鍵id
fid ---------- 商品父id
name ---------- 商品名
最后輸出的數(shù)組格式為
復(fù)制代碼 代碼如下:
<PRE class=php name="code"><PRE class=php name="code">array(
0=>array(
'id'=>1,
'fid'=>0,
'name'=>'法國(guó)貨'
'child'=>array(
0=>array(
'id'=>12,
'fid'=>1,
'name'=>'香水'
'child'=>array(
0=>array(
'id'=>34,
'fid'=>12,
'name'=>'女用香水'
)
)
),
1=>array(
'id'=>13,
'fid'=>1,
'name'=>'筆記本'
'child'=>NUll
)
)
),
1=>array(), //格式同上我就不再重復(fù)寫了 沒什么意義
2=>array()
)</PRE><BR>
<PRE></PRE>
<PRE></PRE>
php代碼:
<P></P>
<P></P>
<PRE class=php name="code"><?php
//數(shù)據(jù)庫(kù)我用的mysql PDO 但是整個(gè)思路又是一樣的
$conn=mysql_connect('localhost','root','123');
if(mysql_errno()){
printf('連接失敗'.mysql_error());
}
mysql_select_db('edeng');
mysql_set_charset('utf8');
/*
*遞歸函數(shù)
*@param id 要查詢fid=$id的所有子類 這里將$id的默認(rèn)值為設(shè)為0 是因?yàn)槲以跀?shù)據(jù)庫(kù)中將最頂層的類別的fid設(shè)置為0
*/
function get_array($id=0){
$sql="select id,fid,cname from e_cat where fid= $id";
$result=mysql_query($sql);
$arr=array();
if($result && mysql_affected_rows()){
while($rows=mysql_fetch_assoc($result)){
$rows['child']=get_array($rows['id']);
$arr[] = $rows;
}
return $arr;
}
}
echo '<pre>';
$result = get_array();
print_r($result);
</PRE><BR>
<BR>
<P></P>
<P> </P>
<P>函數(shù)首先查詢出所有fid為0的類</P>
<P>通過(guò)while逐個(gè)循環(huán)進(jìn)行回調(diào)查找fid為當(dāng)前類的id的子類</P>
<P><BR>
</P>
<P><BR>
</P>
<BR>
<BR>
<PRE></PRE>
</PRE>
php技術(shù):利用php遞歸實(shí)現(xiàn)無(wú)限分類 格式化數(shù)組的詳解,轉(zhuǎn)載需保留來(lái)源!
鄭重聲明:本文版權(quán)歸原作者所有,轉(zhuǎn)載文章僅為傳播更多信息之目的,如作者信息標(biāo)記有誤,請(qǐng)第一時(shí)間聯(lián)系我們修改或刪除,多謝。