Search code examples
phparrayshierarchical

Recursive array searching with proper indexing


I am trying to build a function that allows me to find my way through a complex hierarchical structure.

For example, given this array:

$arr=array("name"=>"NameA","children"=>array());
$arr["children"][]=array("name"=>"NameB","size"=>"38");
$arr["children"][]=array("name"=>"NameC","children"=>array("name"=>'NameD',"children"=>array()));

I would like to find the complete key path to a given name. For example, a search for NameC would return $a=array('children',1) and NameD would return $a=array('children',1,'children'). This would allow me to retrieve NameD with $arr['children'][1]['children']['name'] or $arr[$a[0]][$a[1]][$a[2]]['name'].

I've experimented with calls to this function at each level:

function recursive_array_search($needle,$haystack) {
  foreach($haystack as $key=>$value) {
    $current_key=$key;
    if($needle===$value OR (is_array($value) && recursive_array_search($needle,$value) !== false)) {
        return $current_key;
    }
  }
  return false;
}

But recursive_array_search('NameC') returns 'children' instead of returning 1. I've tried modifying this in multiple ways, but to no avail.

Note that I can't change the structure of the original array because I'm using this to build a JSON array that needs to have this structure.

Any help would be appreciated.


Solution

  • I gather path in array

    function recursive_array_search($needle,$haystack) {
      foreach($haystack as $key=>$value) {
    // found - create array and put lower key
        if($needle===$value) return(array($key));
        if (is_array($value) && ($ret = recursive_array_search($needle,$value)) !== false) 
    // add current key as 1st item in array
        { array_unshift($ret, $key); return $ret; }
      }
      return false;
    }
    

    So, recursive_array_search('NameD',$arr) return:

     Array ( 
        [0] => children
        [1] => 1
        [2] => children
        [3] => name 
    )