>  기사  >  백엔드 개발  >  php_php 기술에서 트리를 순회하는 일반적인 방법 요약

php_php 기술에서 트리를 순회하는 일반적인 방법 요약

WBOY
WBOY원래의
2016-05-16 20:13:36896검색

이 기사의 예에서는 PHP에서 트리를 순회하는 일반적인 방법을 설명합니다. 참고할 수 있도록 모든 사람과 공유하세요. 세부 내용은 다음과 같습니다.

1. 재귀적 깊이 우선 알고리즘:

<&#63;php
define('DS', DIRECTORY_SEPARATOR);
function rec_list_files($from = '.')
{
  if(!is_dir($from)) {
    return array();
  }
  $files = array();
  if($dh = opendir($from))
  {
    while(false !== ($file = readdir($dh))) {
      if($file == '.' || $file == '..') {
        continue;
      }
      $path = $from . DS . $file;
       
      if (is_file($path)) {
        $files[] = $path;
      }
      $files = array_merge($files, rec_list_files($path));
    }
    closedir($dh);
  }
  return $files;
}
function profile($func, $trydir)
{
  $mem1 = memory_get_usage();
  echo '<pre class="brush:php;toolbar:false">----------------------- Test run for '.$func.'() ';
  flush();
  $time_start = microtime(true);
  $list = $func($trydir);
  //print_r($list);
  $time = microtime(true) - $time_start;
  echo 'Finished : '.count($list).' files
'; $mem2 = memory_get_peak_usage(); printf('
Max memory for '.$func.'() : %0.2f kbytes Running time for '.$func.'() : %0.f s
', ($mem2-$mem1)/1024.0, $time); return $list; } profile('rec_list_files', "D:\www\server"); ?>

2. 재귀적 깊이 우선 알고리즘(스택을 사용하여 구현)

<&#63;php
define('DS', DIRECTORY_SEPARATOR);
function deep_first_list_files($from = '.')
{
  if(!is_dir($from)) {
    return false;
  }
  $files = array();
  $dirs = array($from);
  while(NULL !== ($dir = array_pop($dirs))) {
    if( $dh = opendir($dir)) {
      while( false !== ($file = readdir($dh))) {
        if($file == '.' || $file == '..') {
          continue;
        }
        $path = $dir . DS . $file;
        if(is_dir($path)) {
          $dirs[] = $path;
        } else {
          $files[] = $path;
        }
      }
      closedir($dh);
    }
  }
  return $files;
}
function profile($func, $trydir)
{
  $mem1 = memory_get_usage();
  echo '<pre class="brush:php;toolbar:false">----------------------- Test run for '.$func.'() ';
  flush();
  $time_start = microtime(true);
  $list = $func($trydir);
  //print_r($list);
  $time = microtime(true) - $time_start;
  echo 'Finished : '.count($list).' files
'; $mem2 = memory_get_peak_usage(); printf('
Max memory for '.$func.'() : %0.2f kbytes Running time for '.$func.'() : %0.f s
', ($mem2-$mem1)/1024.0, $time); return $list; } profile('deep_first_list_files', "D:\www\server"); ?>

3. 비재귀적 너비 우선 알고리즘(큐를 사용하여 구현됨)

<&#63;php
define('DS', DIRECTORY_SEPARATOR);
function breadth_first_files($from = '.') {
  $queue = array(rtrim($from, DS).DS);// normalize all paths
  $files = array();
  while($base = array_shift($queue )) {
    if (($handle = opendir($base))) {
      while (($child = readdir($handle)) !== false) {
        if( $child == '.' || $child == '..') {
          continue;
        }
        if (is_dir($base.$child)) {
          $combined_path = $base.$child.DS;
          array_push($queue, $combined_path);
        } else {
          $files[] = $base.$child;
        }
      }
      closedir($handle);
    } // else unable to open directory => NEXT CHILD
  }
  return $files; // end of tree, file not found
}
function profile($func, $trydir)
{
  $mem1 = memory_get_usage();
  echo '<pre class="brush:php;toolbar:false">----------------------- Test run for '.$func.'() ';
  flush();
  $time_start = microtime(true);
  $list = $func($trydir);
  //print_r($list);
  $time = microtime(true) - $time_start;
  echo 'Finished : '.count($list).' files
'; $mem2 = memory_get_peak_usage(); printf('
Max memory for '.$func.'() : %0.2f kbytes Running time for '.$func.'() : %0.f s
', ($mem2-$mem1)/1024.0, $time); return $list; } profile('breadth_first_files', "D:\www\server"); ?>

이 기사가 모든 사람의 PHP 프로그래밍 설계에 도움이 되기를 바랍니다.

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.