2011-06-08 84 views
1

我想找到這個陣的最大深度:PHP:節點深度

Array 
(
    [0] => Array 
     (
      [children] => Array 
       (
        [0] => Array 
         (
          [children] => Array 
           (
            [0] => Array 
             (
              [children] => 
             ) 
           ) 
         ) 
       ) 
      [children] => Array 
       (
        [0] => Array 
         (
          [children] => 
         ) 
       ) 
     ) 
) 

在這種情況下,它是3,因爲其中一個節點包含兩個子節點。

這是我一直在努力,到目前爲止代碼:

public static function nodeDepth($nodes) { 
    $node_depth = array(); 
    foreach($nodes as $node) { 
     foreach($node['children'] as $childnode) { 
     $node_depth[] = nodeDepth($childnode)+1; 
     } 
    } 
    return max($node_depth); 
    } 

回答

3

試試這個:

<?php 

    function array_depth($array) { 
     $max_depth = 1; 

     foreach ($array as $value) { 
      if (is_array($value)) { 
       $depth = array_depth($value) + 1; 

       if ($depth > $max_depth) { 
        $max_depth = $depth; 
       } 
      } 
     }   
     return $max_depth; 
    } 

?> 

在你的情況下與子節點,你將需要2

劃分結果

格爾茨,

XpertEase