Reverse recursive in array to find parent id

Webkungen

Trying to figure out a way of getting the parent ID of an item in a multi dimensional array:

$Arr = array(
    array(
        "Id" => 1,
        "Parent" => 0,
        "Children" => array(
            array(
                "Id" => 2,
                "Parent" => 1,
                "Children" => array(),
            ),
            array(
                "Id" => 3,
                "Parent" => 1,
                "Children" => array(
                    array(
                        "Id" => 4,
                        "Parent" => 3,
                        "Children" => array(),
                    ),  
                ),
            ),
        ),
    ), 
    array(
        "Id" => 5,
        "Parent" => 0,
        "Children" => array(
            array(
                "Id" => 6,
                "Parent" => 5,
                "Children" => array(),
            ),
        ),
    )
);

I need to get the "Id" for the top element where "Parent" = 0. I.e. for the item with Id 4 it should return 1 as result, or a search for 6 would return 5. I have tried various ways of recursive function but only manage to get the correct result when the depth is 2.

I have found this function but it seems to return the name of the key rather than the value:

function find_parent($array, $needle, $parent = null) {
    foreach ($array as $key => $value) {

        if (is_array($value)) {
            $pass = $parent;
            if (is_string($key)) {
                $pass = $key;
            }
            $found = find_parent($value, $needle, $pass);
            if ($found !== false) {
                return $found;
            }
        } else if ($key === 'Id' && $value === $needle) {
            return $parent;
        }
    }

    return false;
}

Edit

The following only works on the 1st level/depth:

function GetParent($Data = array(), $Needle = 0){
    foreach($Data as $Key => $Item){
        if($Item['Id'] === $Needle && $Item['Parent'] == 0){
            return $Item['Id'];             
        }
        if(sizeof($Item['Children']) !== 0)
            GetParent($Item['Children'], $Item['Parent']);

    }
    return false;
}

I don't understand what I'm doing wrong.

sevavietl

While it is not usually speed efficient, but PHP has a really great feature in the Standard PHP Library (SPL) called Iterators. Anong them you can find RecursiveArrayIterator which saves you from writing the recursive functions for yourself. In you case, you have to redefine two of its methods:

class CustomRecursiveIterator extends RecursiveArrayIterator
{
    public function hasChildren() {
        return !empty($this->current()['Children']) && is_array($this->current()['Children']);
    }

    public function getChildren()
    {
        return new static($this->current()['Children']);
    }
}

Doing so, you can be sure that you will loop over children, but not all array elements.

Given this class you can write function that will suit your needs:

function getParentId($id, array $array)
{
    $iterator = new RecursiveIteratorIterator(
        new CustomRecursiveIterator($array),
        RecursiveIteratorIterator::CHILD_FIRST 
    );

    $childFound = false;
    foreach ($iterator as $item) {
        if (
            $childFound
            && isset($item['Parent'])
            && $item['Parent'] === 0
            && isset($item['Id'])
        ) {
            return $item['Id'];
        }

        if (isset($item['Id']) && $item['Id'] === $id) {
            $childFound = true;
        }
    }

    return null;
}

Pay attention to this flag RecursiveIteratorIterator::CHILD_FIRST.

Be aware that this implementation will not work if your array structure is invalid. For example, if there is a child with given id, but it doesn't have an ancestor with zero-parent, it will return the next element with zero-parent.

Here is working demo.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Find parent id from nested array

From Dev

Find parent id from nested array

From Dev

Printing Array In Reverse Order using Recursive function

From Dev

Using recursive function to reverse the second half of an array

From Dev

Find Top level Parent and With Recursive CTE

From Dev

RECURSIVE CTE SQL - Find next available Parent

From Dev

Delete all recursive children IDs with parent ID

From Dev

Get parent key of array in a recursive function in PHP

From Dev

how to write a recursive method in java to reverse the values stored in an integer array?

From Dev

Find the parent key value of array

From Dev

get parent array name after array_walk_recursive function

From Dev

Recursive way to find number of items in a object of array

From Dev

Mongoose/MongoDb find documents with reverse reference in an array

From Dev

set id for each element in recursive array

From Dev

Find group of elements in recursive parent-child with XPath

From Dev

Find group of elements in recursive parent-child with XPath

From Dev

mysql select recursive parent id error Unknown column in 'where clause'

From Dev

PHP Sorting array by id and parent id

From Dev

Jquery find id or form outside parent

From Dev

How to find a child with the parent's id in Laravel?

From Dev

Selenium: find the id of the parent of a certain item

From Dev

Recursive function to reverse a string

From Dev

Recursive Reverse Link Lists

From Dev

How to find neighbor element of array 1 from reverse of the same array

From Dev

How to find parent id by click on child id and then child id by getting parent id via jquery

From Dev

Find a model where an ID is in an array

From Dev

find and loop items in array by id

From Dev

Shopify - find a product ID in array

From Dev

how to find a parent id if child id is given in shell script

Related Related

  1. 1

    Find parent id from nested array

  2. 2

    Find parent id from nested array

  3. 3

    Printing Array In Reverse Order using Recursive function

  4. 4

    Using recursive function to reverse the second half of an array

  5. 5

    Find Top level Parent and With Recursive CTE

  6. 6

    RECURSIVE CTE SQL - Find next available Parent

  7. 7

    Delete all recursive children IDs with parent ID

  8. 8

    Get parent key of array in a recursive function in PHP

  9. 9

    how to write a recursive method in java to reverse the values stored in an integer array?

  10. 10

    Find the parent key value of array

  11. 11

    get parent array name after array_walk_recursive function

  12. 12

    Recursive way to find number of items in a object of array

  13. 13

    Mongoose/MongoDb find documents with reverse reference in an array

  14. 14

    set id for each element in recursive array

  15. 15

    Find group of elements in recursive parent-child with XPath

  16. 16

    Find group of elements in recursive parent-child with XPath

  17. 17

    mysql select recursive parent id error Unknown column in 'where clause'

  18. 18

    PHP Sorting array by id and parent id

  19. 19

    Jquery find id or form outside parent

  20. 20

    How to find a child with the parent's id in Laravel?

  21. 21

    Selenium: find the id of the parent of a certain item

  22. 22

    Recursive function to reverse a string

  23. 23

    Recursive Reverse Link Lists

  24. 24

    How to find neighbor element of array 1 from reverse of the same array

  25. 25

    How to find parent id by click on child id and then child id by getting parent id via jquery

  26. 26

    Find a model where an ID is in an array

  27. 27

    find and loop items in array by id

  28. 28

    Shopify - find a product ID in array

  29. 29

    how to find a parent id if child id is given in shell script

HotTag

Archive