#### 1. 無限級分類數(shù)據(jù) --- **本文章中的算法使用的都是以下數(shù)據(jù)** ```php $array = [ ['id' => 1, 'pid' => 0, 'name' => '河南省'], ['id' => 2, 'pid' => 0, 'name' => '山東省'], ['id' => 3, 'pid' => 0, 'name' => '四川省'], ['id' => 4, 'pid' => 1, 'name' => '鄭州市'], ['id' => 5, 'pid' => 1, 'name' => '開封市'], ['id' => 6, 'pid' => 4, 'name' => '金水區(qū)'], ['id' => 7, 'pid' => 5, 'name' => '蘭考縣'], ]; ``` #### 2. 使用引用算法轉(zhuǎn)為無限級分類樹 --- ``` $data = getTree($data); ``` ```php /** * 數(shù)據(jù)格式轉(zhuǎn)換 * 將數(shù)據(jù)轉(zhuǎn)為無限級分類樹 */ function getTree($arr) { $refer = []; $tree = []; foreach ($arr as $k => $v) { //創(chuàng)建主鍵的數(shù)組引用 $refer[$v['id']] = & $arr[$k]; } foreach ($arr as $k => $v) { //上級id $pid = $v['pid']; if ($pid == 0) { //頂級欄目 $tree[] = & $arr[$k]; } else { if (isset($refer[$pid])) { //如果存在上級欄目,則將當前欄目添加到上級欄目的子欄目中 $refer[$pid]['subcat'][] = & $arr[$k]; } } } return $tree; } ```