$categories = array(
array('typeid' => 1, 'parentid' => 0, 'name' => 'Category 1'),
array('typeid' => 2, 'parentid' => 0, 'name' => 'Category 2'),
array('typeid' => 3, 'parentid' => 1, 'name' => 'Subcategory 1.1'),
array('typeid' => 4, 'parentid' => 1, 'name' => 'Subcategory 1.2'),
array('typeid' => 5, 'parentid' => 3, 'name' => 'Sub-subcategory 1.1.1'),
array('typeid' => 6, 'parentid' => 2, 'name' => 'Subcategory 2.1')
);
function getResult($categories){
$result = [];
// 遍历分类数组
foreach ($categories as $category) {
$parentId = $category['parentid'];
$categoryId = $category['typeid'];
if (!isset($result[$parentId])) {
$result[$parentId] = array();
}
$result[$parentId][] = $categoryId;
}
foreach ($result as $parentId => &$children) {
$descendants = array();
foreach ($children as $childId) {
$descendants = array_merge($descendants, self::getChildren($childId,
$result));
}
$children = array_unique(array_merge($children, $descendants));
}
return $result;
}
//定义一个方法
function getChildren($categoryId, $categories) {
$children = array();
if (isset($categories[$categoryId])) {
foreach ($categories[$categoryId] as $childId) {
$children[] = $childId;
$children = array_merge($children, self::getChildren($childId,
$categories));
}
}
return $children;
}
var_dump(getResult($categories));
//打印结果
array(4) {
[0]=>
array(6) {
[0]=>
int(1)
[1]=>
int(2)
[2]=>
int(3)
[3]=>
int(5)
[4]=>
int(4)
[5]=>
int(6)
}
[1]=>
array(3) {
[0]=>
int(3)
[1]=>
int(4)
[2]=>
int(5)
}
[3]=>
array(1) {
[0]=>
int(5)
}
[2]=>
&array(1) {
[0]=>
int(6)
}
}
php 获取无限极 父级下面所有的子级(包含子级的子级)
最新推荐文章于 2023-10-13 17:27:46 发布