PHP Infinite Level classification (with layer depth) algorithm

Source: Internet
Author: User
The code is as follows Copy Code


<?php
$cates = Array (
Array
' CID ' => 1,
' CNAME ' => ' news ',
' PID ' => 0
),

Array
' CID ' => 2,
' CNAME ' => ' notice ',
' 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 notice ',
' PID ' => 2
),

Array
' CID ' => 8,
' CNAME ' => ' general notice ',
' PID ' => 2
),
);

/**
* Generate Menu
*
* @param array $data raw data
* @param integer $pid Parent ID of the current category
* @return Array processing data
*/
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 if there are subcategories
*
* @param integer $cid ID of the current category
* @param array $data raw data
* @return Boolean whether there are sub categories
*/
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.