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
    You could play with http://php.net/manual/en/class.recursivearrayiterator.php – Scuzzy Aug 14 '18 at 11:27
  • this might help https://stackoverflow.com/questions/8656682/getting-all-children-for-a-deep-multidimensional-array – atoms Aug 14 '18 at 11:32

2 Answers2

6

Something like this should do it:

$result = [];
array_walk_recursive($input, function($value, $key) use(&$result) {
    if ($key === 'id') {
        $result[] = $value;
    }
});
Jeto
  • 14,596
  • 2
  • 32
  • 46
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);