Php unlimited classification (with layer depth) Algorithm

Source: Internet
Author: User

An infinitely class php program that uses arrays. If you have any need, you can refer to them. Here we will not talk much about directly copying the code.

The Code is as follows: Copy code


<? Php
$ Cates = array (
Array (
'Cid' => 1,
'Cname' => 'News ',
'Pid '=> 0
),

Array (
'Cid' => 2,
'Cname' => 'notification ',
'Pid '=> 0
),

Array (
'Cid' => 3,
'Cname' => 'domestic news ',
'Pid '=> 1
),

Array (
'Cid' => 4,
'Cname' => 'International news ',
'Pid '=> 1
),

Array (
'Cid' => 5,
'Cname' => 'Beijing news ',
'Pid '=> 3
),

Array (
'Cid' => 6,
'Cname' => 'shanghai news ',
'Pid '=> 3
),

Array (
'Cid' => 7,
'Cname' => 'emergency notification ',
'Pid '=> 2
),

Array (
'Cid' => 8,
'Cname' => 'General notification ',
'Pid '=> 2
),
);

/**
* Generate menu
*
* @ Param array $ raw data
* @ Param integer $ parent id of the current pid category
* @ Return array data after processing
*/
Function createMenuTree ($ data = array (), $ pid = 0)
{
If (empty ($ data ))
{
Return array ();
}

Static $ level = 0;

$ ReturnArray = array ();

Foreach ($ data as $ node)
{
If ($ node ['pid '] = $ pid)
{
$ ReturnArray [] = array (
'Cid' => $ node ['cid'],
'Cname' => $ node ['cname'],
'Level' => $ level
);

If (hasChild ($ node ['cid'], $ data ))
{
$ Level ++;

$ ReturnArray = array_merge ($ returnArray, createMenuTree ($ data, $ node ['cid']);

$ Level --;
}
}
}

Return $ returnArray;
}

/**
* Check whether subcategories exist.
*
* @ Param integer $ cid id of the current category
* @ Param array $ raw data
* @ Return boolean indicates whether a subcategory exists.
*/
Function hasChild ($ cid, $ data)
{
$ HasChild = false;

Foreach ($ data as $ node)
{
If ($ node ['pid '] = $ cid)
{
$ HasChild = true;
Break;
}
}

Return $ hasChild;
}

Header ('content-Type: text/html; charset = UTF-8 ');

$ Result = createMenuTree ($ cates );

Foreach ($ result as $ row)
{
For ($ I = 0; $ I <$ row ['level']; $ I ++)
{
Echo "t ";
}

Echo $ row ['cname']. "n ";
}
?>


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.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.