HartleySan
HartleySan

Reputation: 7810

How can I recursively get the IDs of all the parent elements in a multidimensional array?

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

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?

Upvotes: 2

Views: 1971

Answers (2)

Vahid Alvandi
Vahid Alvandi

Reputation: 612

this program work just in first array deep and not work by this

$arr = array( array( 'id' => 1, //start root 'parent' => array( array( 'id' => 2, 'parent' => array( array( 'id' => 3, 'parent' => array(array('id' => 4,'parent' => array()),array('id' => 5,'parent' => array())), ),

      array(
        'id' => 6,
        'parent' => array(array('id' => 7,'parent' => array()),array('id' => 8,'parent' => array())),
      ),

     ),
  ), 
        array(
    'id' => 9,
    'parent' => array(
      array(
        'id' => 10,
        'parent' => array(array('id' => 11,'parent' => array()),array('id' => 12,'parent' => array())),
      ),

      array(
        'id' => 13,
        'parent' => array(array('id' => 14,'parent' => array()),array('id' => 15,'parent' => array())),
      ),

     ),
  ), 

),  //end root  

),

);

Upvotes: 0

Deimoks
Deimoks

Reputation: 728

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

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

Call this function like this: get_parents('101', $arr);

In your example, the result would be:

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

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

Upvotes: 2

Related Questions