2

Hai first take a look at this array,

Array
(
    [0] => Array
        (
            [id] => 4
            [parent_id] => 3
            [children] => Array
                (
                    [0] => Array
                        (
                            [id] => 7
                            [parent_id] => 4
                            [children] => Array
                                (
                                    [0] => Array
                                        (
                                            [id] => 6
                                            [parent_id] => 7
                                            [children] => Array
                                                (
                                                    [0] => Array
                                                        (
                                                            [id] => 2
                                                            [parent_id] => 6
                                                        )

                                                )

                                        )

                                )

                        )

                )

        )

    [1] => Array
        (
            [id] => 5
            [parent_id] => 3
        )

)

i need a output of all id [IE: 4, 7, 6, 2, 5] was the desired result i need something like

foreach ($tree as $j) {
    echo $j['id'];
    if($j['children']){

    }

but how to loop it out to get all the child's? i am not able to catch all the child elements or else i am getting strucked onto an infinite loop is how to get the desired result in php? any suggestions will be really appreciated!

2

2 Answers 2

6

Something like this should do it:

$result = [];
array_walk_recursive($input, function($value, $key) use(&$result) {
    if ($key === 'id') {
        $result[] = $value;
    }
});
Sign up to request clarification or add additional context in comments.

Comments

1

You must use a recursive function like:

function getIds($tree) {
        foreach ($tree as $j) {
            echo $j['id'];
            if(isset($j['children'])){
                getIds($j['children']);
            }
        }
    }

And in the main just need:

getIds($tree);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.