Re: [PHP] Need routine to tell me number of dimensions in array.
[email protected] (Robert Cummings)
| Newsgroups | php.general |
|---|---|
| Organization | InterJinn |
| Message-ID | <[email protected]> |
Jim Lucas wrote:
> 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
Globals are dirty for this kind of recursive utility function. Here's a
cleaner example:
<?php
function get_array_depth( $array )
{
if( !is_array( $array ) )
{
return 0;
}
$maxDepth = 0;
foreach( $array as $value )
{
if( ($subDepth = get_array_depth( $value )) > $maxDepth )
{
$maxDepth = $subDepth;
}
}
return 1 + $maxDepth;
}
?>
Cheers,
Rob.
--
http://www.interjinn.com
Application and Templating Framework for PHP