如何递归获取多维数组中所有父元素的ID? [英] How can I recursively get the IDs of all the parent elements in a multidimensional array?

查看:809
本文介绍了如何递归获取多维数组中所有父元素的ID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下PHP多维数组,该数组旨在通过以下方式进行递归:

Let's say I have the following PHP multidimensional array, which is designed to be recursed through:

$arr = array(
  array(
    'id' => 1,
    'kids' => array(
      array(
        'id' => 11,
        'kids' => array(
          array(
            'id' => 101,
            'kids' => array(),
          ),
        ),
      ), // please note this is a sample
    ),   // it could have any number of levels
  ),
);

在ID值为101的情况下,如何确定ID 1和11是多维数组中该元素的父级?

How, given an ID value of 101, can I figure out that IDs 1 and 11 are parents of that element in the multidimensional array?

推荐答案

我编写了一个可能对您有帮助的函数.

I wrote a function that may be helpful for you.

function get_parents($target, $array)
{
    $parents_id = false;
    foreach ($array as $item) {
        if (empty($array)) 
            return;
        if ($item['id'] == $target)
            return array();
        else
            $parents_id = get_parents($target, $item['kids']);
        if (is_array($parents_id))
            array_unshift($parents_id, $item['id']);

    }
    return $parents_id;
}

对于数组中的每个项目,如果为空,则什么也不返回.如果这是您要查找的项目,请返回一个空数组,在其中我们将添加父母的ID,否则请继续查找.此时,如果$ parents_id是一个数组,则是因为您已找到目标键,因此将父级ID添加到数组的开头

For each item in your array, if it is empty, just return nothing. If it is the item you are looking for, return an empty array in which we will add parent's ids, else keep looking deeper. At this point, if $parents_id is an array, is because you have found your target key, so add parents ids to the beginning of your array

像这样调用此函数:get_parents('101', $arr);

在您的示例中,结果将是:

In your example, the result would be:

Array
(
    [0] => 1
    [1] => 11
)

如果未找到目标键,则该函数返回false.

If the target key is not found, the function returns false.

这篇关于如何递归获取多维数组中所有父元素的ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆