让所有孩子获得深度多维数组 [英] Getting all children for a deep multidimensional array

查看:91
本文介绍了让所有孩子获得深度多维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的数组:

array(
    array(
        'id' => 1,
        'children' => array(
            array(
                'id' => 2,
                'parent_id' => 1
            ),
            array(
                'id' => 3,
                'parent_id' => 1,
                'children' => array(
                    array(
                        'id' => 4,
                        'parent_id' => 3
                    )
                )
            )
        )
    )
);

如果有必要,阵列会更深入。我需要为任何给定的ID获取孩子。

The array goes deeper if it's necessary. I need to get the children for any given id.

谢谢。

推荐答案

function getChildrenOf($ary, $id)
{
  foreach ($ary as $el)
  {
    if ($el['id'] == $id)
      return $el;
  }
  return FALSE; // use false to flag no result.
}

$children = getChildrenOf($myArray, 1); // $myArray is the array you provided.

除非我遗漏了什么,否则迭代数组寻找与<$ c $相匹配的东西c> id key和你正在寻找的id(然后返回它作为结果)。您也可以迭代搜索(并给我一秒钟发布代码,这将检查 parentId 键)...

Unless I'm missing something, iterate over the array looking for something that matches the id key and the id you're looking for (then return it as a result). You can also iteratively search (and give me a second to post code for that, which would examine the parentId key instead)...

-

递归版,包含儿童元素:

function getChildrenFor($ary, $id)
{
  $results = array();

  foreach ($ary as $el)
  {
    if ($el['parent_id'] == $id)
    {
      $results[] = $el;
    }
    if (count($el['children']) > 0 && ($children = getChildrenFor($el['children'], $id)) !== FALSE)
    {
      $results = array_merge($results, $children);
    }
  }

  return count($results) > 0 ? $results : FALSE;
}

递归版,不包括儿童元素

function getChildrenFor($ary, $id)
{
  $results = array();

  foreach ($ary as $el)
  {
    if ($el['parent_id'] == $id)
    {
      $copy = $el;
      unset($copy['children']); // remove child elements
      $results[] = $copy;
    }
    if (count($el['children']) > 0 && ($children = getChildrenFor($el['children'], $id)) !== FALSE)
    {
      $results = array_merge($results, $children);
    }
  }

  return count($results) > 0 ? $results : FALSE;
}

这篇关于让所有孩子获得深度多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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