PHP將資料集轉換成樹狀結構
阿新 • • 發佈:2019-01-09
/** * 把返回的資料集轉換成Tree * @param array $list 要轉換的資料集 * @param string $pid parent標記欄位 * @param string $level level標記欄位 * @return array */ function list_to_tree($list, $pk='id', $pid = 'pid', $child = '_child', $root = 0) { // 建立Tree $tree = array(); if(is_array($list)) { // 建立基於主鍵的陣列引用$refer = array(); foreach ($list as $key => $data) { $refer[$data[$pk]] =& $list[$key]; } foreach ($list as $key => $data) { // 判斷是否存在parent $parentId = $data[$pid]; if ($root == $parentId) { $tree[] =& $list[$key]; }else{ if (isset($refer[$parentId])) { $parent =& $refer[$parentId]; $parent[$child][] =& $list[$key]; } } } } return $tree; } /** * 將list_to_tree的樹還原成列表 * @param array $tree 原來的樹 * @param string $child 孩子節點的鍵 * @param string $order 排序顯示的鍵,一般是主鍵 升序排列 * @param array $list 過渡用的中間陣列, * @return array 返回排過序的列表陣列*/ function tree_to_list($tree, $child = '_child', $order='id', &$list = array()){ if(is_array($tree)) { $refer = array(); foreach ($tree as $key => $value) { $reffer = $value; if(isset($reffer[$child])){ unset($reffer[$child]); tree_to_list($value[$child], $child, $order, $list); } $list[] = $reffer; } $list = list_sort_by($list, $order, $sortby='asc'); } return $list; }