Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

Determining how 'deep' an element of a multidimensional array is

Posted on 2009-04-02
2
Medium Priority
?
202 Views
Last Modified: 2012-05-06
I need to determine how 'deep' an element is within a multidimensional array. For example, following the code snippet, how can I determine whether an element is in the first level, the second level, the third level, etc.? How can I determine that "Vancouver" is nested three levels deep?

Ideally I would be looking for a return of an integer - so looking for "Countries" would return 0, "USA" would return 1, "Seattle" would return 2, etc.
$myArray = array(
		"Countries" => array(
				"Canada" => array(
						"Vancouver", "Toronto"),
				"USA" => array(
						"New York", "Seattle"),
				     ),
		);

Open in new window

0
Comment
Question by:radarhill
2 Comments
 
LVL 39

Accepted Solution

by:
Roger Baklund earned 2000 total points
ID: 24055662
Try this:
function howDeep($a,$target,$level=0) {
  if(in_array($target,array_keys($a)))
    return $level;
  foreach($a as $key=>$sub_array) {
    if(is_array($sub_array)) {
      $tmp = howDeep($sub_array,$target,$level+1);
      if($tmp) 
        return $tmp;
    } elseif($sub_array==$target)
      return $level;
  }
  return false;
}
echo howDeep($myArray,'Seattle');

Open in new window

0
 
LVL 1

Author Comment

by:radarhill
ID: 24056056
Perfect - thanks!
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Things That Drive Us Nuts Have you noticed the use of the reCaptcha feature at EE and other web sites?  It wants you to read and retype something that looks like this. Insanity!  It's not EE's fault - that's just the way reCaptcha works.  But it i…
Part of the Global Positioning System A geocode (https://developers.google.com/maps/documentation/geocoding/) is the major subset of a GPS coordinate (http://en.wikipedia.org/wiki/Global_Positioning_System), the other parts being the altitude and t…
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
Suggested Courses

876 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question