利用php遞迴實現無限分類 格式化數組的詳解

來源:互聯網
上載者:User

我們要做一個商品的無限分類
首先資料庫欄位為:
id ----------商品主鍵id
fid ---------- 商品父id
name ---------- 商品名
最後輸出的數組格式為
複製代碼 代碼如下:<PRE class=php name="code"><PRE class=php name="code">array(
0=>array(
'id'=>1,
'fid'=>0,
'name'=>'法國貨'
'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(), //格式同上我就不再重複寫了 沒什麼意義
2=>array()
)</PRE><BR>
<PRE></PRE>
<PRE></PRE>
php代碼:
<P></P>
<P></P>
<PRE class=php name="code"><?php
//資料庫我用的mysql PDO 但是整個思路又是一樣的
$conn=mysql_connect('localhost','root','123');
if(mysql_errno()){
printf('串連失敗'.mysql_error());
}
mysql_select_db('edeng');
mysql_set_charset('utf8');
/*
*遞迴函式
*@param id 要查詢fid=$id的所有子類 這裡將$id的預設值為設為0 是因為我在資料庫中將最頂層的類別的fid設定為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>函數首先查詢出所有fid為0的類</P>
<P>通過while逐個迴圈進行回調尋找fid為當前類的id的子類</P>
<P><BR>
</P>
<P><BR>
</P>
<BR>
<BR>
<PRE></PRE>
</PRE>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.