php获取当前栏目下所有子级id

文章描述:

php指定id获取下面的所有子级ID方法

 

// 查找所有子级id方法
function getAllChildren($parentId, $items) {
    $children = array();
    foreach ($items as $item) {
        if ($item['p_id'] == $parentId) {
            $children[] = $item;
            $grandChildren = getAllChildren($item['id'], $items);
            if (!empty($grandChildren)) {
                $children = array_merge($children, $grandChildren);
            }
        }
    }
    return $children;
}

 

// 示例数据
$items = [
    ['id' => 1, 'name'=>'手机', 'p_id' => 0],
    ['id' => 2, 'name'=>'电脑', 'p_id' => 0],
    ['id' => 3, 'name'=>'vivo', 'p_id' => 1],
    ['id' => 4, 'name'=>'oppo', 'p_id' => 1],
    ['id' => 5, 'name'=>'戴尔电脑', 'p_id' => 2],
    ['id' => 6, 'name'=>'iqoo7', 'p_id' => 3],
    // ... 更多项目
];

 

// 获取ID为1的所有子项
$children = getAllChildren(1, $items);
print_r($children);

结果:

(
    [0] => Array
        (
            [id] => 3
            [name] => vivo
            [p_id] => 1
        )

    [1] => Array
        (
            [id] => 6
            [name] => iqoo7
            [p_id] => 3
        )

    [2] => Array
        (
            [id] => 4
            [name] => oppo
            [p_id] => 1
        )

)

 

 

// 把顶级也包含进去
$arr = [1];
foreach ($children as $child) {
	array_push($arr,$child['id']);
}


print_r($arr);

结果:

Array
(
    [0] => 1
    [1] => 3
    [2] => 6
    [3] => 4
)

 

发布时间:2024/10/30

发表评论