This article mainly introduces PHP recursive traversal of multi-dimensional arrays to achieve unlimited classification. it involves PHP recursive traversal of arrays related techniques and is very useful in linking menus and parent and child columns design, for more information about how to use PHP to recursively traverse multi-dimensional arrays, see the following example. We will share this with you for your reference. The details are as follows:
1, 'parentid' => 0, 'name' => 'China', 'IMG '=> '000000 '); $ data [] = array ('id' => 1, 'parentid' => 0, 'name' => 'China '); $ data [] = array ('id' => 2, 'parentid' => 0, 'name' => 'u.s '); $ data [] = array ('id' => 3, 'parentid' => 0, 'name' => 'Korea '); $ data [] = array ('id' => 4, 'parentid' => 1, 'name' => 'Beijing '); $ data [] = array ('id' => 5, 'parentid' => 1, 'name' => 'Shanghai '); $ data [] = array ('id' => 6, 'parentid' => 1, 'name' => 'Guangxi '); $ data [] = array ('id' => 7, 'parentid' => 6, 'name' => 'gui Lin '); $ data [] = array ('id' => 8, 'parentid' => 6, 'name' => 'nanning '); $ data [] = array ('id' => 9, 'parentid' => 6, 'name' => 'Liuzhou '); $ data [] = array ('id' => 10, 'parentid' => 2, 'name' => 'Newyork '); $ data [] = array ('id' => 11, 'parentid' => 2, 'name' => 'Washington '); $ data [] = array ('id' => 12, 'parentid' => 3, 'name' => 'Seoul '); $ tree = build_tree ($ data, 0); // echo memory_get_usage (); print_r ($ tree); function findChild (& $ arr, $ id) {$ childs = array (); foreach ($ arr as $ K => $ v) {if ($ v ['parentid'] ==$ id) {$ childs [] = $ v ;}} return $ childs ;} function build_tree ($ rows, $ root_id) {$ childs = findChild ($ rows, $ root_id); if (empty ($ childs) {return null ;} foreach ($ childs as $ k =>$ v) {$ rescurTree = build_tree ($ rows, $ v ['id']); if (null! = $ RescurTree) {$ childs [$ k] ['Childs '] = $ rescurTree;} return $ childs ;}?>
Running result:
Array ([0] => Array ([id] => 1 [parentid] => 0 [name] => China [childs] => Array ([0] => Array ([id] => 4 [parentid] => 1 [name] => Beijing) [1] => Array ([id] => 5 [parentid] => 1 [name] => Shanghai) [2] => Array ([id] => 6 [parentid] => 1 [name] => Guangxi [childs] => Array ([0] => Array ([ id] => 7 [parentid] => 6 [name] => Guilin) [1] => Array ([id] => 8 [parentid] => 6 [name] => Nanning) [2] => Array ([id] => 9 [parentid] => 6 [name] => Liuzhou ))))) [1] => Array ([id] => 2 [parentid] => 0 [name] => US [childs] => Array ([0] => Array ([ id] => 10 [parentid] => 2 [name] => New York) [1] => Array ([id] => 11 [parentid] => 2 [name] => Washington ))) [2] => Array ([id] => 3 [parentid] => 0 [name] => Korea [childs] => Array ([0] => Array ([ id] => 12 [parentid] => 3 [name] => Seoul ))))
I hope this article will help you with PHP programming.
For more articles about how PHP recursively traverses multi-dimensional arrays to implement unlimited classification, refer to PHP Chinese network!