php - 如何递归获取多维数组中所有父元素的ID?

标签 php arrays recursion multidimensional-array

假设我有以下 PHP 多维数组,它被设计为递归:

$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 是多维数组中该元素的父元素?

最佳答案

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

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是一个数组,是因为你已经找到了你的目标key,所以将parents id添加到你的数组的开头

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

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

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

如果没有找到目标键,函数返回false

关于php - 如何递归获取多维数组中所有父元素的ID?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26704931/

相关文章:

带有游标和 View 的 MySQL 递归存储过程不刷新

java - 递归:扫描数字中数字的频率:redux

c# - C# 中的迭代正则表达式捕获

php - 选中时从复选框中获取值并将其发送到 mySQL

arrays - 遍历数组 - 只打印一次?

python - 将元组列表转换为结构化的 numpy 数组

java - Java 中的循环问题

php - Laravel Controller 和包中的路由?

javascript - 如何在同一页面上处理表单(前端和后端)?

php - 如何在 Codeigniter Active Records 中使用 'DISTINCT'?