Re: [PHP] Need routine to tell me number of dimensions in array.

[email protected] (Jim Lucas)
Newsgroups php.general
Message-ID <[email protected]>
Daevid Vincent wrote:
> Anyone have a function that will return an integer of the number of
> dimensions an array has?
> 
> I did some quick searches and came up with nothing. 
> The closest was here of someone asking the same thing, but his solution
> isn't right:
> http://www.bigresource.com/PHP-count-array-dimensions-VrIahx1b.html
> http://php.net/manual/en/function.count.php
> 
> From a human standpoint, it's easy to see, "oh, this is a TWO
> dimensional"...
> 

How about this...  Using a slightly modified array that you posted, I came up
with this in about 10 minutes

<pre>I am working with the following data structure

<?php

$in = array(
  0 => array(
    0 => array('Flight Number', 'flight_number'),
    1 => array(
        0 => array('Timestamp Departure', 'timestamp_departure'),
        1 => array('Timestamp Arrival', 'timestamp_arrival'),
      )
    ),
  1 => array('Departure City', 'departure_city'),
  2 => array('Arrival City', 'arrival_city'),
);

print_r($in);

echo "\n\n";

$max_depth = 0;
$cur_depth = 0;
function max_array_depth($ar) {
	global $cur_depth, $max_depth;
	if ( is_array($ar) ) {
		$cur_depth++;
		if ( $cur_depth > $max_depth ) {
			$max_depth = $cur_depth;
		}
		foreach ( $ar AS $row ) {
			max_array_depth($row);
		}
		$cur_depth--;
	}
}

max_array_depth($in);

echo "Max depth of array is: {$max_depth}";

?></pre>

http://www.cmsws.com/examples/php/testscripts/[email protected]/0002.php

-- 
Jim Lucas
NOC Manager
541-323-9113
BendTel, Inc.
http://www.bendtel.com
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.