Search code examples
phparraysrecursionmultidimensional-arrayiterator

Getting all children for a deep multidimensional array


I have array like this:

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
                    )
                )
            )
        )
    )
);

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

Thanks.


Solution

  • 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.
    

    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)...

    --

    Recursive Version, Includes Children Elements:

    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;
    }
    

    Recursive Version, Excluding Children Elements

    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;
    }