Php recursive method to implement unlimited classification instances

Source: Internet
Author: User

Array:

The code is as follows: Copy code

$ Items = array (
Array ('id' => 1, 'pid '=> 0, 'name' => 'Level 1 11 '),
Array ('id' => 11, 'pid '=> 0, 'name' => 'Level 1 12 '),
Array ('id' => 2, 'pid '=> 1, 'name' => 'Level 2 21 '),
Array ('id' => 10, 'pid '=> 11, 'name' => 'Level 2 22 '),
Array ('id' => 3, 'pid '=> 1, 'name' => 'second 23 '),
Array ('id' => 12, 'pid '=> 11, 'name' => 'second-level 24 '),
Array ('id' => 13, 'pid '=> 12, 'name' => 'third-level 31 '),
Array ('id' => 9, 'pid '=> 1, 'name' => 'second level 25 '),
);

Function:

The code is as follows: Copy code

Function formatTree ($ array, $ pid = 0 ){
$ Arr = array ();
$ Tem = array ();
Foreach ($ array as $ v ){
If ($ v ['pid '] ==$ pid ){
$ Tem = formatTree ($ array, $ v ['id']);
// Determine whether a subarray exists
$ Tem & $ v ['son'] = $ tem;
$ Arr [] = $ v;
  }
 }
Return $ arr;
}

The array must contain the hierarchical relationship between id and pid to specify the array value.

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.