PHP數(shù)組無限分級數(shù)據(jù)的層級化處理代碼
/**
* 創(chuàng)建父節(jié)點樹形數(shù)組
* 參數(shù)
* $ar 數(shù)組,鄰接列表方式組織的數(shù)據(jù)
* $id 數(shù)組中作為主鍵的下標或關聯(lián)鍵名
* $pid 數(shù)組中作為父鍵的下標或關聯(lián)鍵名
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]];
$t[$k]['reference'] = true;
}
}
return $t;
}
/**
* 創(chuàng)建子節(jié)點樹形數(shù)組
* 參數(shù)
* $ar 數(shù)組,鄰接列表方式組織的數(shù)據(jù)
* $id 數(shù)組中作為主鍵的下標或關聯(lián)鍵名
* $pid 數(shù)組中作為父鍵的下標或關聯(lián)鍵名
**/
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];
$t[$k]['reference'] = true;
}
}
return $t;
}
示例:
$p = find_parent($data, 'ID', 'PARENT');
$c = find_child($data, 'ID', 'PARENT');
上面兩種方法是將所有節(jié)點按id平攤到一個數(shù)組中,然后找到他們的 parent 或 children ,通過引用將 平攤的元素掛接到 parent 、children 下,
但被引用的元素依然存在于平攤的數(shù)組中,因此,在實際應用時,最好標記那些被引用的元素,以避免以他們?yōu)楦_始遍歷,導致重復。
foreach ($p as $key => $item) {
if($item['reference']) continue;
print_r($item);
}
foreach ($c as $key => $item) {
if($item['reference']) continue;
print_r($item);
}
遞歸法,PHP 數(shù)組元素被刪除后,數(shù)組游標會歸零,因此在遍歷過程中一些已經(jīng)找到 “歸宿” 的元素也不得不留在數(shù)組中,無法縮減后繼元素的搜索范圍:
$mylist = array(array( 'parent_id'=>0,'id'=>1),
array( 'parent_id'=>0,'id'=>2),
array( 'parent_id'=>0,'id'=>3),
array( 'parent_id'=>2,'id'=>4),
array( 'parent_id'=>2,'id'=>5),
array( 'parent_id'=>3,'id'=>6),
array( 'parent_id'=>3,'id'=>7),
array( 'parent_id'=>4,'id'=>8),
array( 'parent_id'=>5,'id'=>9),
array( 'parent_id'=>5,'id'=>10)
);
function _findChildren($list, $p_id){ //數(shù)據(jù)層級化,
$r = array();
foreach($list as $id=>$item){
if($item['parent_id'] == $p_id) {
$length = count($r);
$r[$length] = $item;
if($t = $this->_findChildren($list, $item['id']) ){
$r[$length]['children'] = $t;
}
}
}
return $r;
}
print_r(_findChildren($mylist, 0));
相關文章
PHP橋接模式Bridge Pattern的優(yōu)點與實現(xiàn)過程
這篇文章主要介紹了PHP橋接模式Bridge Pattern的優(yōu)點與實現(xiàn)過程,橋接模式是一種結(jié)構(gòu)型模式,它將抽象部分與實現(xiàn)部分分離開來,使它們可以獨立地變化2023-03-03
php實現(xiàn)有序數(shù)組旋轉(zhuǎn)后尋找最小值方法
在本篇文章中我們給大家詳細分享了php實現(xiàn)有序數(shù)組旋轉(zhuǎn)后尋找最小值方法,有需要的朋友們可以學習下。2018-09-09
WordPress中注冊菜單與調(diào)用菜單的方法詳解
這篇文章主要介紹了WordPress中注冊菜單與調(diào)用菜單的方法詳解,分別依靠register_nav_menus()函數(shù)與wp_nav_menu()函數(shù)的使用,需要的朋友可以參考下2015-12-12
php-redis中的sort排序函數(shù)總結(jié)
這篇文章主要介紹了php-redis中的sort排序函數(shù)總結(jié),本文講解了了按字母排序、排序取部分數(shù)據(jù)、使用外部key進行排序等排序方法,同時給出代碼實例,需要的朋友可以參考下2015-07-07

