PHP樹-不需要遞歸的實現(xiàn)方法
更新時間:2016年06月21日 16:53:01 投稿:jingxian
下面小編就為大家?guī)硪黄狿HP樹-不需要遞歸的實現(xiàn)方法。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
PHP樹-不需要遞歸的實現(xiàn)方法
/** * 創(chuàng)建父節(jié)點樹形數(shù)組 * 參數(shù) * $ar 數(shù)組,鄰接列表方式組織的數(shù)據(jù) * $id 數(shù)組中作為主鍵的下標或關(guān)聯(lián)鍵名 * $pid 數(shù)組中作為父鍵的下標或關(guān)聯(lián)鍵名 * 返回 多維數(shù)組 **/ 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]]; } } return $t; } /** * 創(chuàng)建子節(jié)點樹形數(shù)組 * 參數(shù) * $ar 數(shù)組,鄰接列表方式組織的數(shù)據(jù) * $id 數(shù)組中作為主鍵的下標或關(guān)聯(lián)鍵名 * $pid 數(shù)組中作為父鍵的下標或關(guān)聯(lián)鍵名 * 返回 多維數(shù)組 **/ 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]; } } return $t; } $data = array( array('ID'=>1, 'PARENT'=>0, 'NAME'=>'祖父'), array('ID'=>2, 'PARENT'=>1, 'NAME'=>'父親'), array('ID'=>3, 'PARENT'=>1, 'NAME'=>'叔伯'), array('ID'=>4, 'PARENT'=>2, 'NAME'=>'自己'), array('ID'=>5, 'PARENT'=>4, 'NAME'=>'兒子'), ); $p = find_parent($data, 'ID', 'PARENT'); $c = find_child($data, 'ID', 'PARENT'); Print_r ($c);
執(zhí)行效果:
Array ( [1] => Array ( [ID] => 1 [PARENT] => 0 [NAME] => 祖父 [child] => Array ( [2] => Array ( [ID] => 2 [PARENT] => 1 [NAME] => 父親 [child] => Array ( [4] => Array ( [ID] => 4 [PARENT] => 2 [NAME] => 自己 [child] => Array ( [5] => Array ( [ID] => 5 [PARENT] => 4 [NAME] => 兒子 ) ) ) ) ) [3] => Array ( [ID] => 3 [PARENT] => 1 [NAME] => 叔伯 ) ) ) [2] => Array ( [ID] => 2 [PARENT] => 1 [NAME] => 父親 [child] => Array ( [4] => Array ( [ID] => 4 [PARENT] => 2 [NAME] => 自己 [child] => Array ( [5] => Array ( [ID] => 5 [PARENT] => 4 [NAME] => 兒子 ) ) ) ) ) [3] => Array ( [ID] => 3 [PARENT] => 1 [NAME] => 叔伯 ) [4] => Array ( [ID] => 4 [PARENT] => 2 [NAME] => 自己 [child] => Array ( [5] => Array ( [ID] => 5 [PARENT] => 4 [NAME] => 兒子 ) ) ) [5] => Array ( [ID] => 5 [PARENT] => 4 [NAME] => 兒子 ) )
以上這篇PHP樹-不需要遞歸的實現(xiàn)方法就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
您可能感興趣的文章:
相關(guān)文章
使用php批量刪除數(shù)據(jù)庫下所有前綴為prefix_的表
這篇文章主要介紹了php如何批量刪除數(shù)據(jù)庫下所有前綴為prefix_的表,需要的朋友可以參考下2014-06-06解決PHPstudy Apache無法啟動的問題【親測有效】
這篇文章主要介紹了PHPstudy Apache無法啟動的問題及解決方法【親測有效】,本文給大家總結(jié)了三種方法供大家參考,需要的朋友可以參考下2020-10-10php下幾個常用的去空、分組、調(diào)試數(shù)組函數(shù)
dump() 把數(shù)組以數(shù)組格式數(shù)組,有益于調(diào)試 array_chunk() php默認函數(shù) 作用是把函數(shù)平均分組2009-02-02ThinkPHP實現(xiàn)更新數(shù)據(jù)實例詳解(demo)
本文給大家介紹thinkphp實現(xiàn)更新數(shù)據(jù)的實例詳解以及thinkphp更新數(shù)據(jù)庫的五種方法,本文介紹的非常不錯,具有參考借鑒價值,感興趣的朋友可以參考下2016-06-06PHP使用Memcache時模擬命名空間及緩存失效問題的解決
這篇文章主要介紹了PHP使用Memcache時模擬命名空間及緩存失效問題的解決,這里談到的緩存失效主要針對高并發(fā)場景下取不到緩存的情況,需要的朋友可以參考下2016-02-02