最近在做一個商城項目時候,需要取出分類表中的數據,分類表中通過一個pid(父類id)關聯各個分類,為了整理讀出的二維數據成一個樹狀的格式,自己在項目中封裝了下面一個方法。
<code><span>/** * [treeCats description] *<span> @param</span> [array] $arr [原始未排序的数组] *<span> @param</span> [array] $limit [第一个元素代表开始递归的parent_id,默认为0,第二个元素代表剔除元素及子元素cat_id,如果没有传值,默认为0] *<span> @param</span> integer $level [函数调用的深度] *<span> @return</span> [array] [排好序的数组] */</span><span>public</span><span><span>function</span><span>treeCats</span><span>(<span>$arr</span>,<span>$limit</span>,<span>$level</span>=<span>0</span>)</span>{</span><span>$rec</span> = <span>array</span>(); <span>//先消除cat_id对应的值</span><span>foreach</span> (<span>$arr</span><span>as</span><span>$key</span>=><span>$value</span>){ <span>if</span>(<span>$value</span>[<span>'cat_id'</span>]!=<span>$limit</span>[<span>'cd'</span>]){ <span>$arr_new</span> [<span>$key</span>]=<span>$value</span>; } } <span>//对于新数组进行遍历</span><span>foreach</span> (<span>$arr_new</span><span>as</span><span>$key</span> => <span>$value</span>) { <span>if</span>(<span>$value</span>[<span>'parent_id'</span>]==<span>$limit</span>[<span>"pd"</span>] &&<span>$value</span>[<span>'parent_id'</span>]!=<span>$limit</span>[<span>"cd"</span>]){ <span>$value</span>[<span>'level'</span>]=<span>$level</span>; <span>$rec</span> []= <span>$value</span>; <span>//生成用于下一层循环的数组</span><span>$next_limit</span> = <span>array</span>(<span>"pd"</span>=><span>$value</span>[<span>'cat_id'</span>],<span>"cd"</span>=><span>$limit</span>[<span>"cd"</span>]); <span>$rec</span> = array_merge(<span>$rec</span>,<span>$this</span>->treeCats(<span>$arr</span>,<span>$next_limit</span>,<span>$level</span>+<span>1</span>)); } } <span>return</span><span>$rec</span>; } </code>
這裡設定$limit 的應用場景是如果修改這個分類的父分類為它原來的子分類的話,這個分類枝就發生丟失了,所以這時候就應該將可選類裡面剔除它的子類。
以上就介紹了php實戰之使用遞歸讀取商品無限分類,包括了方面的內容,希望對PHP教程有興趣的朋友有所幫助。