douxin1956 2012-08-23 07:40
浏览 51

递归 - 查找具有最多子项的元素

I have a PHP object (or it could be an array) and I want to iterate through its elements and all of its child elements recursively, and find which element has the most number of children.

This is what I have done.

var $max_element = array();

$this->find_longest_element_recursively($data, 0, array());

public function find_longest_element_recursively($object, $index, $max_array) {

  if(!is_array((array) $object) || is_string($object) || is_numeric($object) || is_bool($object)) {

  } else {
    foreach($object as $key => $element) {
      if(sizeof((array) $element) > sizeof((array) $this->max_array)) {
        $this->max_array = $element;
      }
      $this->find_longest_element_recursively($element, $index+1, $max_array);
    }
  }     
}

ok. So this works for me. But I just don't think this is the proper way of doing a recursion. I think I can get rid of that $max_element variable and return the actual max_element object as a result of the recursive function, but unsure of how to keep track of the max_element object during the recursion. Love to hear your thoughts. Thanks in advance.

  • 写回答

1条回答 默认 最新

  • duanbu1421 2012-08-23 07:48
    关注

    You could enclose this in a class :

    class MaxFinder {
    
        var $max_element = array();
        function MaxFinder() {
        }
    
        public function find_longest_element_recursively($object, $index, $max_array) {
    
          if(!is_array((array) $object) || is_string($object) || is_numeric($object) || is_bool($object)) {
    
          } else {
            foreach($object as $key => $element) {
              if(sizeof((array) $element) > sizeof((array) $this->max_array)) {
                $this->max_array = $element;
              }
              $this->find_longest_element_recursively($element, $index+1, $max_array);
            }
          }     
         }
    
         public get_longest_element($object, $index, $max_array) {
              $this->find_longest_element_recursively($object, $index, $max_array);
              return $this->max_element;
         }
    }
    

    This would offer you a one call only computation and not clutter your variable space :

     $result = (new MaxFinder()).get_longest_element_recursively($data, 0, array());
    

    Of course you could also make a static function doing for you the instanciation and the get_... call.

    评论

报告相同问题?

悬赏问题

  • ¥15 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序
  • ¥15 onvif+openssl,vs2022编译openssl64
  • ¥15 iOS 自定义输入法-第三方输入法
  • ¥15 很想要一个很好的答案或提示