1

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.

Leonid Glanz
1,2612 gold badges16 silver badges37 bronze badges
asked May 15, 2015 at 17:14

1 Answer 1

1

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 
)
answered May 15, 2015 at 18:11
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.