Several examples of converting php arrays into trees

Source: Internet
Author: User
Tags php code

Php code

The code is as follows: Copy code
 
* $ SourceArr original array
* $ Key PRIMARY key
* $ Parent key associated with the primary key
* $ Child key name generated by childrenKey
*
*/
 
Function arrayToTree ($ sourceArr, $ key, $ parentKey, $ childrenKey)

$ TempSrcArr = array ();
Foreach ($ sourceArr as $ v)
    { 
$ TempSrcArr [$ v [$ key] = $ v;
    } 
$ I = 0;
$ Count = count ($ sourceArr );
For ($ I = ($ count-1); $ I & gt; = 0; $ I --)
    { 
If (isset ($ tempSrcArr [$ sourceArr [$ I] [$ parentKey])
        { 
$ TArr = array_pop ($ tempSrcArr );
$ TempSrcArr [$ tArr [$ parentKey] [$ childrenKey] = (isset ($ tempSrcArr [$ tArr [$ parentKey] [$ childrenKey]) & amp; is_array ($ tempSrcArr [$ tArr [$ parentKey] [$ childrenKey])? $ TempSrcArr [$ tArr [$ parentKey] [$ childrenKey]: array ();
Array_push ($ tempSrcArr [$ tArr [$ parentKey] [$ childrenKey], $ tArr );
        } 
    } 
Return $ tempSrcArr;

 

 
Php code
 
* Convert an array into a tree
* Example: convert array (
Array ('id' => 1, 'parentid' => 0, 'name' => 'name1 ')
, Array ('id' => 2, 'parentid' => 0, 'name' => 'name2 ')
, Array ('id' => 4, 'parentid' => 1, 'name' => 'name1 _ 4 ')
, Array ('id' => 15, 'parentid' => 1, 'name' => 'name1 _ 5 ')
); Convert
* Array (
[1] => Array ([id] => 1
[ParentId] => 0
[Name] => name1
[Children] => Array (
[0] => Array ([id] => 15, [parentId] => 1, [name] => name1_5)
[1] => Array ([id] => 4, [parentId] => 1, [name] => name1_4)
                )
        )
[2] => Array ([id] => 2, [parentId] => 0, [name] => name2)
)
* @ Param array $ array to be converted by sourceArr
* @ Param string $ confirm the parent and child keys in the key array. In this example, "id" is used"
* @ Param string $ parent key in the parentKey array. In this example, it is "parentId"
* @ Param type $ childrenKey: index the key of the subnode on the tree node. In this example, it is "children"
* @ Return array returns the generated tree
*/

The code is as follows: Copy code
Function arrayToTree ($ sourceArr, $ key, $ parentKey, $ childrenKey)

$ TempSrcArr = array ();
 
$ AllRoot = TRUE;
Foreach ($ sourceArr as $ v)
    { 
$ IsLeaf = TRUE;
Foreach ($ sourceArr as $ cv)
        { 
If ($ v [$ key])! = $ Cv [$ key])
            { 
If ($ v [$ key] ==$ cv [$ parentKey])
                { 
$ IsLeaf = FALSE;
                } 
If ($ v [$ parentKey] = $ cv [$ key])
                { 
$ AllRoot = FALSE;
                } 
            } 
        } 
If ($ isLeaf)
        { 
$ LeafArr [$ v [$ key] = $ v;
        } 
$ TempSrcArr [$ v [$ key] = $ v;
    } 
If ($ allRoot)
    { 
Return $ tempSrcArr;
    } 
Else
    { 
Unset ($ v, $ cv, $ sourceArr, $ isLeaf );
Foreach ($ leafArr as $ v)
        { 
If (isset ($ tempSrcArr [$ v [$ parentKey])
            { 
$ TempSrcArr [$ v [$ parentKey] [$ childrenKey] = (isset ($ tempSrcArr [$ v [$ parentKey] [$ childrenKey]) & is_array ($ tempSrcArr [$ v [$ parentKey] [$ childrenKey])? $ TempSrcArr [$ v [$ parentKey] [$ childrenKey]: array ();
Array_push ($ tempSrcArr [$ v [$ parentKey] [$ childrenKey], $ v );
Unset ($ tempSrcArr [$ v [$ key]);
            } 
        } 
Unset ($ v );
Return arrayToTree ($ tempSrcArr, $ key, $ parentKey, $ childrenKey );
    } 

 

 
 
Php code
/** Recursive method :**/
 
$ Rows = array (
0 => array ('id' => 1, 'name' => 'menu 1', 'parentid' => 0)
, 1 => array ('id' => 2, 'name' => 'menu 2', 'parentid' => 0)
, 2 => array ('id' => 3, 'name' => 'menu 3', 'parentid' => 0)
, 3 => array ('id' => 4, 'name' => 'menu 1_1 ', 'parentid' => 1)
, 4 => array ('id' => 5, 'name' => 'menu 1_2 ', 'parentid' => 1)
, 5 => array ('id' => 6, 'name' => 'menu 2_1 ', 'parentid' => 2)
);
Print_r (getTree ($ rows, 0, 'id', 'parentid '));

The code is as follows: Copy code
 
/**
* The array generates a tree based on the parent id.
* @ Staticvar int $ depth recursive depth
* @ Param array $ data array data
* @ Param integer $ the value of the pid parent id
* @ Param string $ key id key value in the $ data array
* @ Param string $ chrildKey the child key to be generated
* @ Param string $ the key value of the pKey parent id in the $ data array
* @ Param int $ maxDepth maximum recursive depth to prevent infinite recursion
* @ Return array the restructured array
*/
Function getTree ($ data, $ pid = 0, $ key = 'id', $ pKey = 'parentid', $ childKey = 'child ', $ maxDepth = 0 ){
Static $ depth = 0;
$ Depth ++;
If (intval ($ maxDepth) <= 0)
    { 
$ MaxDepth = count ($ data) * count ($ data );
    } 
If ($ depth> $ maxDepth)
    { 
Exit ("error recursion: max recursion depth {$ maxDepth }");
    } 
$ Tree = array ();
Foreach ($ data as $ rk => $ rv)
    { 
If ($ rv [$ pKey] ==$ pid)
        { 
$ Rv [$ childKey] = getTree ($ data, $ rv [$ key], $ key, $ pKey, $ childKey, $ maxDepth );
$ Tree [] = $ rv;
        } 
    } 
Return $ tree;

One instance

The code is as follows: Copy code

<! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<Html xmlns = "http://www.w3.org/1999/xhtml">
<Head>
<Meta http-equiv = "Content-Type" content = "text/html; charset = utf-8"/>
<Script type = "text/javascript" src = "http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"> </script>
<Title> TREE </title>
<Style type = "text/css">
/* Global CSS of the tree */
. Kyp_tree {
Font: 12px/2.5 verdana;
Float: left; display: inline;
}
. Kyp_tree dd {
Margin: 0; padding: 0;
Margin-left: 20px;
}
/* Link */
. Kyp_tree dl {
Font-size: 12px;
Color: #333;
Text-decoration: none;
}
. Kyp_tree dl a: hover,. kyp_tree dd dt. red_sub {
Font-size: 12px;
Color: # AE0002;
}
/* Level 1 dl */
. Kyp_tree dl {
Border-bottom: 1px dashed # ccc;
Margin: 0; padding: 0;
}
/* Sub-dl */
. Kyp_tree dl,. kyp_tree dl. last {
Border: none;
}
. Kyp_tree dd dt. currentClass {
Background: url(tree_top.gif) no-repeat 0-24px;
}
/* Level 1 title */
. Kyp_tree dt {
Background: url(tree_top.gif) no-repeat 2px-57px;
Padding-left: 15px;
Cursor: pointer;
Font-size: 13px;
Height: 30px;
Line-height: 27px;
Line-height: 32px9;
}
/* Subtitle */
. Kyp_tree dd dt {
Background: url(tree_arrow.gif) no-repeat 2px 10px;
Font-size: 12px;
}
/* Level 1 open style */
. Kyp_tree dt. open {
Background: url(tree_top.gif) no-repeat 2px 12px;
}
/* Open style */
. Kyp_tree dd dt. open {
Background: url(tree_arrow.gif) no-repeat 0-25px;
}
/* No subnode style */
. Kyp_tree dt. nosub {
Background: none;
}
</Style>
<Script type = "text/javascript">
// <! [CDATA [
JQuery. fn. createTree = function (fn, ini ){
Var $ = jQuery, ini = Object (ini );
This. find ('DD'). hide ();
This. children ('dl: Lak'). addClass ('la ');
This. find ('dt', this). each (function (){
Var nosub = $ (this). next ('DD'). size () = 0;
If (nosub ){
$ (This). addClass ('nosub ');
}
If (ini. id & ini. id ==$ (this). attr ('classify ')){
$ (This). parents ('DD'). show (). prev ('DT '). addClass ('open ');
$ (This). addClass ('Red _ sub ');
If (nosub ){
$ (This). addClass ('currentclass ')
} Else {
$ (This). next ('DD'). show ();
$ (This). addClass ('open ')
}
}
}). Click (function (e ){
Var dd = $ (this). next ('DD '),
IsClose = dd.css ('display') = 'none ';
If (dd. size ()){
If (isClose ){
Dd. show ();
$ (This). addClass ('open ')
} Else {
Dd. hide ();
$ (This). removeClass ('open ')
}
}
Return fn & fn. call (this, e, dd)
});
If (ini. mx ){
This. find ('dt'). click (function (e ){
Var J = $ (this );
If (J. next ('DD'). size ()){
If (J. hasClass ('open ')){
J. parent (). siblings ('dl '). children ('DD'). hide ();
J. parent (). siblings ('dl '). children ('DT'). removeClass ('open ');
J. next ('DD'). show ();
J. addClass ('open ')
}
}
})
}
};
(Function ($ ){
$ (Function (){
$ ('# Tree_wrap'). createTree (function (e, dd) {// Callback (event, next dd)
Certificate ('{show'{.html (this. innerHTML + dd. size ())
}, {Mx: 1, id: 200}) // whether the mx is mutually exclusive. The current category of the id
});
}) (JQuery)
//]>
</Script>
</Head>
<Body>

<? Php

// The Order of the tree Group is the order of classification. Therefore, when the sub-classes of the classification must follow the same sequence
$ Tree = array (
1 => array ('id' => 1, 'cname' => 'Level 1 category', 'pid' => 0 ),

100 => array ('id' => 100, 'cname' => 'specially added Level 2 category', 'pid' => 1 ),
101 => array ('id' => 101, 'cname' => 'second-level classification 2222222222 ', 'pid' => 1 ),

2 => array ('id' => 2, 'cname' => 'second-level category', 'pid '=> 1 ),
3 => array ('id' => 3, 'cname' => 'third-level category', 'pid' => 2 ),
4 => array ('id' => 4, 'cname' => 'level 4 category', 'pid' => 3 ),
5 => array ('id' => 5, 'cname' => 'level 4 classification 2', 'pid' => 3 ),
200 => array ('id' => 200, 'cname' => '000000', 'pid' => 5 ),
6 => array ('id' => 6, 'cname' => 'another level category', 'pid '=> 0 ),
7 => array ('id' => 7, 'cname' => 'first First first', 'pid '=> 0 ),
8 => array ('id' => 8, 'cname' => 'first First first', 'pid '=> 7 ),
);

// Specify the Category ID and return the subclass quantity (no deep recursion is performed)
Function getChildTotal ($ id)
{
Global $ tree;
$ Total = 0;
Foreach ($ tree as $ value)
{
If ($ id = $ value ['pid'])
{
$ Total ++;
}
}
Return $ total;
}

 

// Specify the Category ID, www.111cn.net, and return an array (without deep recursion)
Function getChildArray ($ id)
{
Global $ tree;
$ Array = array ();
Foreach ($ tree as $ key => $ value)
{
If ($ id = $ value ['pid'])
{
$ Array [$ key] = $ value;
}
}
Return $ array;
}


// Recursive query converts a tree array into an HTML nested tree

Function getTreeHTML ($ tree, $ level = 0)
{
If ($ tree)
{
$ Level + = 1;
Foreach ($ tree as $ id => $ node)
{
$ Html. = "<dl> ";
$ Html. = '<dt classify = "'. $ node ['id']. '"> <a href =" http://www.baidu.com/"> '. $ node ['cname']. "</a> </dt> ";
If (getChildTotal ($ node ['id'])
{
$ Tree_last = getChildArray ($ node ['id']);

$ Html. = '<dd> ';
$ Html. = getTreeHTML ($ tree_last, $ level );
$ Html. = '</dd> ';

}
$ Html. = '</dl> ';
}
}
Return $ html;
}

$ Html = getTreeHTML (getChildArray (0 ));
Echo '<div id = "tree_wrap" class = "kyp_tree"> ';
Echo $ html;
Echo '</div> <div id = "show" style = "clear: both; border-top: 1px solid red"> </div> ';

?>
</Body>
</Html>

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.