最近在做一个商城项目时候,需要取出分类表中的数据,分类表中通过一个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教程有兴趣的朋友有所帮助。