php 實現不用遞迴的樹形陣列建構函式 無限級分類
阿新 • • 發佈:2019-01-31
/** * 建立父節點樹形陣列 * 引數 * $ar 陣列,鄰接列表方式組織的資料 * $id 陣列中作為主鍵的下標或關聯鍵名 * $pid 陣列中作為父鍵的下標或關聯鍵名 * 返回 多維陣列 **/ function find_parent($ar, $id='id', $pid='pid') { foreach($ar as $v) $t[$v[$id]] = $v; foreach ($t as $k => $item){ if( $item[$pid] ){ if( ! isset($t[$item[$pid]]['parent'][$item[$pid]]) ) $t[$item[$id]]['parent'][$item[$pid]] =& $t[$item[$pid]]; } } var_dump($t); } /** * 建立子節點樹形陣列 * 引數 * $ar 陣列,鄰接列表方式組織的資料 * $id 陣列中作為主鍵的下標或關聯鍵名 * $pid 陣列中作為父鍵的下標或關聯鍵名 * 返回 多維陣列 **/ function find_child($ar, $id='id', $pid='pid') { foreach($ar as $v) $t[$v[$id]] = $v; foreach ($t as $k => $item){ if( $item[$pid] ) { $t[$item[$pid]]['child'][$item[$id]] =& $t[$k]; } } var_dump($t); } $data = array( array('ID'=>1, 'PARENT'=>0, 'NAME'=>'祖父','des'=>'祖父是一個和藹可親的人.'), array('ID'=>2, 'PARENT'=>1, 'NAME'=>'父親','des'=>'父親是一個和藹可親的人.'), array('ID'=>3, 'PARENT'=>1, 'NAME'=>'叔伯','des'=>'叔伯是一個和藹可親的人.'), array('ID'=>4, 'PARENT'=>2, 'NAME'=>'自己','des'=>'自己是一個和藹可親的人.'), array('ID'=>5, 'PARENT'=>4, 'NAME'=>'兒子','des'=>'兒子是一個乖順孩子.'), array('ID'=>6, 'PARENT'=>5, 'NAME'=>'孫女','des'=>'孫女是一個乖順孩子.'), array('ID'=>7, 'PARENT'=>5, 'NAME'=>'孫子','des'=>'孫子是一個乖順孩子.'), ); $p = find_parent($data, 'ID', 'PARENT'); $c = find_child($data, 'ID', 'PARENT');