#### 1. 無限級分類數據 --- **本文章中的算法使用的都是以下數據** ```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' => '金水區'], ['id' => 7, 'pid' => 5, 'name' => '蘭考縣'], ]; ``` #### 2. 使用引用算法轉為無限級分類樹 --- ``` $data = getTree($data); ``` ```php /** * 數據格式轉換 * 將數據轉為無限級分類樹 */ function getTree($arr) { $refer = []; $tree = []; foreach ($arr as $k => $v) { //創建主鍵的數組引用 $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; } ```