Solved

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

Posted on 2009-04-02
2
198 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 500 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

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Ajax and PHP 9 53
Add a loading gif while php runs server side 15 63
php date function ( diffrence between two dates ) 6 40
PHP function parameters defined 14 39
Password hashing is better than message digests or encryption, and you should be using it instead of message digests or encryption.  Find out why and how in this article, which supplements the original article on PHP Client Registration, Login, Logo…
Since pre-biblical times, humans have sought ways to keep secrets, and share the secrets selectively.  This article explores the ways PHP can be used to hide and encrypt information.
The viewer will learn how to count occurrences of each item in an array.
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

740 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