JavaScript
// $PATH utils/recursive.js
const recursive = (array, parent = 0) => {
const newArray = []
array.forEach(ele => {
if (ele.parent === parent) {
const item = {
id: ele.id,
label: ele.name,
value: ele.id,
parent: ele.parent
}
const children = recursive(array, ele.id)
if (children.length > 0) {
item.children = children
}
newArray.push(item)
}
})
return newArray
}
export default recursive
测试一下
import recursive from '@/utils/recursive' // 放在utils目录里
const cats = [
{
id: 1,
name: 'name1',
parent: 0
},
{
id: 11,
name: 'name11',
parent: 1
},
{
id: 12,
name: 'name12',
parent: 1
},
{
id: 121,
name: 'name121',
parent: 12
},
{
id: 122,
name: 'name122',
parent: 12
},
{
id: 2,
name: 'name2',
parent: 0
}
]
const recursiveCats = [
{
'children': [
{
'id': 11,
'label': 'name11',
'parent': 1,
'value': 11
},
{
'children': [
{
'id': 121,
'label': 'name121',
'parent': 12,
'value': 121
},
{
'id': 122,
'label': 'name122',
'parent': 12,
'value': 122
}
],
'id': 12,
'label': 'name12',
'parent': 1,
'value': 12
}
],
'id': 1,
'label': 'name1',
'parent': 0,
'value': 1
},
{
'id': 2,
'label': 'name2',
'parent': 0,
'value': 2
}
]
describe('Utils:recursive', () => {
it('recursive cats', () => {
expect(recursive(cats)).toEqual(recursiveCats)
})
})
PHP
function myRecursive(array $array = [], int $parent = 0)
{
$newArray = [];
foreach ($array as $item) {
if ($item['parent'] === $parent) {
$newItem = [
'id' => $item['id'],
'label' => $item['name'],
'value' => $item['id'],
'parent' => $item['parent']
];
$children = myRecursive($array, $item['id']);
if (count($children)) {
$newItem['children'] = $children;
}
$newArray[] = $newItem;
}
}
return $newArray;
}
/**
* 通过引用
*/
function myReferenceRecursive($data = [])
{
$items = [];
foreach ($data as $key => $value) {
$items[$value['id']] = $value;
}
$tree = [];
foreach ($items as $key => $item) {
if (isset($items[$item['parent']])) {
$items[$item['parent']]['children'][] = &$items[$key];
} else {
$tree[] = &$items[$key];
}
}
return $tree;
}
// 测试 test
$cats = '[
{
"id": 1,
"name": "name1",
"parent": 0
},
{
"id": 11,
"name": "name11",
"parent": 1
},
{
"id": 12,
"name": "name12",
"parent": 1
},
{
"id": 121,
"name": "name121",
"parent": 12
},
{
"id": 122,
"name": "name122",
"parent": 12
},
{
"id": 2,
"name": "name2",
"parent": 0
}
]';
$cats = json_decode($cats, true);
print_r(myRecursive($cats));