简体   繁体   中英

Get all children for a given parent id in array

I have an array like this:

array(
    array(
        'id' => 1,
        'parent_id' => null
    ),
    array(
        'id' => 2,
        'parent_id' => 1
    ),
    array(
        'id' => 3,
        'parent_id' => 2
    ),
    array(
        'id' => 4,
        'parent_id' => null
    ),
    array(
        'id' => 5,
        'parent_id' => 4
    )
);

How can i find all the childrens of a given parent_id including all grand children? For example the function will return 2,3 for parent_id 1.

Thanks.

// I corrected the array to fit your result 1 => 2,3

    <?php

    $test = array(
    array(
            'id' => 1,
            'parent_id' => null
    ),
    array(
            'id' => 2,
            'parent_id' => 1
    ),
    array(
            'id' => 3,
            'parent_id' => 1
    ),
    array(
            'id' => 4,
            'parent_id' => null
    ),
    array(
            'id' => 5,
            'parent_id' => 4
    )
    );

    // 1_2+3
    $parent_childs = ARRAY();
    foreach ($test AS $index => $child) {
        if (!isset($child['parent_id'])) { continue; }
        $parent_childs[$child['parent_id']][] = $child['id'];
    }


    echo '<pre>';var_dump($parent_childs); echo '</pre>';

    ?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM