首頁 > 後端開發 > php教程 > php生成無限欄樹

php生成無限欄樹

迷茫
發布: 2023-03-06 22:22:02
原創
3161 人瀏覽過

欄位數組:

$arr=Array(
    Array('cid' => 2,'cname' => '新闻','pid' => 0),
    Array('cid' => 4,'cname' =>'体育','pid' => 0),
    Array('cid' => 5,'cname' => '娱乐','pid' => 0),
    Array('cid' => 7,'cname' => '热点新闻','pid' =>2),
    Array('cid' => 8,'cname' => '小众新闻','pid' => 2),
    Array('cid' => 9,'cname' => '民谣新闻','pid' => 8),
);
登入後複製
<?php
$arr=Array(
    Array(&#39;cid&#39; => 2,&#39;cname&#39; => &#39;新闻&#39;,&#39;pid&#39; => 0),
    Array(&#39;cid&#39; => 4,&#39;cname&#39; =>&#39;体育&#39;,&#39;pid&#39; => 0),
    Array(&#39;cid&#39; => 5,&#39;cname&#39; => &#39;娱乐&#39;,&#39;pid&#39; => 0),
    Array(&#39;cid&#39; => 7,&#39;cname&#39; => &#39;热点新闻&#39;,&#39;pid&#39; =>2),
    Array(&#39;cid&#39; => 8,&#39;cname&#39; => &#39;小众新闻&#39;,&#39;pid&#39; => 2),
    Array(&#39;cid&#39; => 9,&#39;cname&#39; => &#39;民谣新闻&#39;,&#39;pid&#39; => 8),

);
function formatTree($array, $pid = 0,$level = 1,$field = array(&#39;pid&#39;=>&#39;pid&#39;,&#39;id&#39;=>&#39;id&#39;,&#39;children&#39;=>&#39;children&#39;)){
        $arr = array();
        foreach ($array as &$v) {
            if ($v[$field[&#39;pid&#39;]] == $pid) {
                $v[&#39;level&#39;] = $level;
                $tem = formatTree($array, $v[$field[&#39;id&#39;]],$v[&#39;level&#39;]+1,$field);
                //判断是否存在子数组
                $tem && $v[$field[&#39;children&#39;]] = $tem;
                $arr[] = $v;
            }
        }
        return $arr;
    }

$tree = formatTree( $arr,0,1, $field = array(&#39;pid&#39;=>&#39;pid&#39;,&#39;id&#39;=>&#39;cid&#39;,&#39;children&#39;=>&#39;children&#39;) );
echo &#39;<pre class="brush:php;toolbar:false">&#39;;
print_r( $tree);

?>
登入後複製

以上是php生成無限欄樹的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板