PHP Infinite Pole classification

Source: Internet
Author: User
Tags learn php php class

When you learn PHP unlimited pole classification, we all feel a word "difficult" I also find it difficult, so, now are still watching, because the work to use, so, it must be studied.

To the Internet a search PHP infinite classification, a lot, but a lot of is a, and, write very messy, code a lot, let us how to learn, those are not reliable, or self-ramming drum unlimited pole classification.

For example, a category table: with ID, name, PID, sort on these four simple fields, not too complicated.

ID name PID Sort
1 PHP 0 1
2 Javascript 0 2
3 MySQL 0 3
4 PHP Class 1 1
5 Smarty 1 2
6 Private Method 4 1
7 JQuery 2 1


Code: category.class.php

Class Category {
static public Function Sortout ($cate, $pid =0, $level =0, $html = '--') {
$tree = Array ();
foreach ($cate as $v) {
if ($v [' id '] = = $pid) {
$v [' level '] = $level + 1;
$v [' html '] = Str_repeat ($html, $level);
$tree [] = $v;
$tree = Array_merge ($tree, Self::sortout ($cate, $v [' id '], $level +1, $html));
}
}
return $tree;
}
}


The $cate here is a two-dimensional array that queries the table above: It's not written here.

Here are the effects:

ID name PID level sort
1 PHP 0 1 1
4--php Class 1 2 1
6----Private Method 4 3 1
5--smarty 1 2 2
2 Javascript 0 1 2
7--php Class 2 2 1
3 MySQL 0 1 3



In this, we have implemented the simplest PHP infinite classification, which is used in a lot of work.

----------------------------------------------

I don't think I need array_merge.

function tree (& $list, $pid =0, $level =0, $html = '--') {
Static $tree = Array ();
foreach ($list as $v) {
if ($v [' pid '] = = $pid) {
$v [' sort '] = $level;
$v [' html '] = Str_repeat ($html, $level);
$tree [] = $v;
Tree ($list, $v [' id '], $level + 1);
}
}
return $tree;
}

PHP Infinite Pole classification

Related Article

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.