# Ask for a simple recursion

Source: Internet
Author: User
Ask for a simple recursion \$ arr = array (
Array (
'Id' => 1,
'Parentid' => 0,
'Title' => 'A'
),
Array (
'Id' => 2,
'Parentid' => 1,
'Title' => 'A-1'
),
Array (
'Id' => 3,
'Parentid' => 1,
'Title' => 'A-1'
),
Array (
'Id' => 4,
'Parentid' => 2,
'Title' => 'A-1-1'
)
);

Recursive conversion to an array is as follows:
\$ Arr = array (
Array (
'Id' => 1,
'Parentid' => 0,
'Title' => 'A ',
'Child '=> array (
Array (
'Id' => 2,
'Parentid' => 1,
'Title' => 'A-1 ',
'Child '=> array (
......
)
Array (
'Id' => 3,
'Parentid' => 2,
'Title' => 'A-2'
)
),
......
);
How do I write this recursion?

`function findChildren(\$list, \$p=0){  \$r = array();  foreach(\$list as \$id=>\$item){    if(\$item['parentid'] == \$p) {      \$r[\$id] = \$item;      if(\$t = findChildren(\$list, \$item['id']) )        \$r[\$id]['children'][] = \$t;    }  }  return \$r;}        \$arr = array(    array(        'id' => 1,        'parentid' => 0,        'title' => 'a'    ),    array(        'id' => 2,        'parentid' => 1,        'title' => 'a-1'    ),    array(        'id' => 3,        'parentid' => 1,        'title' => 'a-1'    ),    array(        'id' => 4,        'parentid' => 2,        'title' => 'a-1-1'    )  );print_r(findChildren(\$arr));`
Array
(
[0] => Array
(
[Id] => 1
[Parentid] => 0
[Title] =>
[Children] => Array
(
[0] => Array
(
[1] => Array
(
[Id] => 2
[Parentid] => 1
[Title] => A-1
[Children] => Array
(
[0] => Array
(
[3] => Array
(
[Id] => 4
[Parentid] => 2
[Title] => a-1-1
)

)

)

)

[2] => Array
(
[Id] => 3
[Parentid] => 1
[Title] => A-1
)

)

)

)

)
Related Keywords:

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.