douqiao4450 2016-11-09 12:46
浏览 451
已采纳

在数组中反向递归以查找父ID

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.

  • 写回答

1条回答 默认 最新

  • doufang1954 2016-11-09 13:56
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!