Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have array:

$adm_menu_old = array (
    array( 
        'id' => 1,
        'name' => 'Test1',
    ), 
    array( 
        'id' => 3,
        'name' => 'Test3',
        'childrens' => array(
            array(
                'id' => 31,
                'name' => 'Test31',
            ),
            array(
                'id' => 32,
                'name' => 'Test32',
                'childrens' => array(
                     array(
                        'id' => 321,
                        'name' => 'Test321',
                     ),
            ),
        )
    ), 
    array( 
        'id' => 4,
        'name' => 'Test4',
    ), 
);

Say i know id value. I need get path with all parents of this id. For example i need get path to this element: id=321 i need get array with key name values:

array('Test3','Test32','Test321')

how should look like recursive function?

share|improve this question

1 Answer 1

up vote 0 down vote accepted

Try this function:

function getNames($id, $arr) {
  $result = array();
    foreach($arr as $key => $val) {
      if(is_array($val)) {
        if($val["id"] == $id) {
          $result[] = $val["name"];
        } elseif(!empty($val["childrens"]) && is_array($val["childrens"])) {
          $sub_res = getNames($id, $val["childrens"]);
          if(count($sub_res) > 0) {
          $result[] = $val["name"];
          $result = array_merge($result, $sub_res);
        }
      }
    }
  }
  return $result;
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.