Рубрики
Uncategorized

Примеры двух способов реализации бесконечной классификации в PHP [рекурсия и ссылка]

Автор оригинала: David Wong.

В этой статье представлены два способа реализации бесконечной классификации в PHP. Чтобы поделиться с вами для справки, следующим образом: Во время интервью меня спросили о разработке и внедрении бесконечной классификации. Распространенный способ-добавить поле PID, чтобы различать мою собственную классификацию при построении таблицы

$array = array(
Array ('id '= > 1,' PID '= > 0,' name '= > Hebei Province'),
Array ('id '= > 2,' PID '= > 0,' name '= > Beijing'),
Array ('id '= > 3,' PID '= > 1,' name '= > Handan'),
Array ('id '= > 4,' PID '= > 2,' name '= > Chaoyang District'),
Array ('id '= > 5,' PID '= > 2,' name '= > Tongzhou District'),
Array ('id '= > 6,' PID '= > 4,' name '= > Wangjing'),
Array ('id '= > 7,' PID '= > 4,' name '= > Jiuxianqiao'),
Array ('id '= > 8,' PID '= > 3,' name '= > perpetual zone'),
Array ('id '= > 9,' PID '= > 1,' name '= > Wu'an city'),
);

Данные, хранящиеся в базе данных, выглядят следующим образом. Как реализовать бесконечную рекурсию ? Существует два распространенных метода: рекурсия и ссылочный алгоритм

рекурсивный алгоритм

/**
*Recursive implementation of infinite classification
*@ param $array classification data
*@ param $PID parent ID
*@ param $level classification level
*@ return $list directly traverse the sorted array, then $level can be used to traverse the indentation
*/
function getTree($array, $pid =0, $level = 0){
    //Declare static array to avoid array coverage caused by multiple declarations during recursive calls
    static $list = [];
    foreach ($array as $key => $value){
      //The first time, find the node whose parent node is the root node, that is, the node whose PID = 0
      if ($value['pid'] == $pid){
        //The parent node is the node of the root node, and the level is 0, which is the first level
        $value['level'] = $level;
        //Put the array in the list
        $list[] = $value;
        //Remove this node from the array to reduce the subsequent recursion consumption
        unset($array[$key]);
        //Start recursion, find the node whose parent ID is the node ID, and the level is the original level + 1
        getTree($array, $value['id'], $level+1);
      }
    }
    return $list;
}
/*
*Get the recursive data, traverse to generate classification
*/
$array = getTree($array);
foreach($array) as $value{
    echo str_repeat('--', $value['level']), $value['name'].'
'; }

Выходные результаты неограниченная реализация классификации ОК

Провинция Хэбэй –город Ханьдань-Район Юннянь –город Уань Пекин –Район Чаоян-Ванцзин-Район Цзюйсяньцяо –Тунчжоу

Эталонный алгоритм

function generateTree($array){
  //The first step is to construct data
  $items = array();
  foreach($array as $value){
    $items[$value['id']] = $value;
  }
  //The second part traverses the tree structure of data generation
  $tree = array();
  foreach($items as $key => $value){
    if(isset($items[$item['pid']])){
      $items[$item['pid']]['son'][] = &$items[$key];
    }else{
      $tree[] = &$items[$key];
    }
  }
  return $tree;
}
//After the first step, the data is like this
Array
(
  [1] => Array
    (
      [id] => 1
      [pid] => 0
      [name] = > Hebei Province
      [children] => Array
        (
        )
    )
  [2] => Array
    (
      [id] => 2
      [pid] => 0
      [name] = > Beijing
      [children] => Array
        (
        )
    )
  [3] => Array
    (
      [id] => 3
      [pid] => 1
      [name] = > Handan City
      [children] => Array
        (
        )
    )
  [4] => Array
    (
      [id] => 4
      [pid] => 2
      [name] = > Chaoyang District
      [children] => Array
        (
        )
    )
  [5] => Array
    (
      [id] => 5
      [pid] => 2
      [name] = > Tongzhou District
      [children] => Array
        (
        )
    )
  [6] => Array
    (
      [id] => 6
      [pid] => 4
      [name] = > Wangjing
      [children] => Array
        (
        )
    )
  [7] => Array
    (
      [id] => 7
      [pid] => 4
      [name] = > Jiuxianqiao
      [children] => Array
        (
        )
    )
  [8] => Array
    (
      [id] => 8
      [pid] => 3
      [name] = > Yongnian District
      [children] => Array
        (
        )
    )
  [9] => Array
    (
      [id] => 9
      [pid] => 1
      [name] = > Wu'an city
      [children] => Array
        (
        )
    )
)
//The first step is easy to understand, that is, to construct data. Now let's go to step two
 $tree = array();
 //Traverse constructed data
  foreach($items as $key => $value){
  //If the PID node exists
    if(isset($items[$value['pid']])){
      //Put the current $value in the son of the PID node. Note that the reference is passed here. Why?
      $items[$value['pid']]['son'][] = &$items[$key];
    }else{
      $tree[] = &$items[$key];
    }
  }
//The core of this method is reference. The default way of PHP variable value passing is by reference
//That is to say, if the traversal order is Handan City, Hebei Province, when traversing to Hebei Province, it will put Hebei Province into the tree, and when traversing to Handan City, it will put Handan city into the sub node array of Hebei Province, but!!! At this time, Hebei Province has been put in the tree array. According to the rule of PHP variable passing by value, you haven't changed the data of Hebei Province in the tree array, so reference passing is used here
//When you make changes to Hebei Province, Hebei Province in the tree array has also made changes. Let's do an experiment. Let's remove the reference passing and see the results
//Output results with normal value transfer
 Array
(
  [0] => Array
    (
      [id] => 1
      [pid] => 0
      [name] = > Hebei Province
    )
  [1] => Array
    (
      [id] => 2
      [pid] => 0
      [name] = > Beijing
    )
)
//It can be seen that only Hebei Province and Beijing City output it because they are the first level nodes and rank 1 and 2. After they are put into the $tree array, they are not passed by reference. Then the subsequent operations on their child nodes do not take effect in $tree. Now we change the order to put Handan City in front of Hebei Province, so according to our inference So Handan should be in the tree array
//Output of Handan City in front of Hebei Province
Array
(
  [0] => Array
    (
      [id] => 1
      [pid] => 0
      [name] = > Hebei Province
      [son] => Array
        (
          [0] => Array
            (
              [id] => 3
              [pid] => 1
              [name] = > Handan City
            )
        )
    )
  [1] => Array
    (
      [id] => 2
      [pid] => 0
      [name] = > Beijing
    )
)
//It's true that this proves that our inference is correct. Now let's change the reference value back to have a look
//Output results by reference
Array
(
  [1] => Array
    (
      [id] => 1
      [pid] => 0
      [name] = > Hebei Province
      [children] => Array
        (
          [0] => Array
            (
              [id] => 3
              [pid] => 1
              [name] = > Handan City
              [children] => Array
                (
                  [0] => Array
                    (
                      [id] => 8
                      [pid] => 3
                      [name] = > Yongnian District
                    )
                )
            )
          [1] => Array
            (
              [id] => 9
              [pid] => 1
              [name] = > Wu'an city
            )
        )
    )
  [2] => Array
    (
      [id] => 2
      [pid] => 0
      [name] = > Beijing
      [children] => Array
        (
          [0] => Array
            (
              [id] => 4
              [pid] => 2
              [name] = > Chaoyang District
              [children] => Array
                (
                  [0] => Array
                    (
                      [id] => 6
                      [pid] => 4
                      [name] = > Wangjing
                    )
                  [1] => Array
                    (
                      [id] => 7
                      [pid] => 4
                      [name] = > Jiuxianqiao
                    )
                )
            )
          [1] => Array
            (
              [id] => 5
              [pid] => 2
              [name] = > Tongzhou District
            )
        )
    )
)
//The tree structure outputs perfectly. The core of this method is to reference and pass values

Для получения дополнительной информации о PHP читатели, интересующиеся PHP, могут обратиться к темам нашего веб-сайта: Учебник по структуре данных и алгоритмам PHP, краткое изложение алгоритмов программирования PHP, краткое изложение использования строк PHP, навыки работы с массивами PHP, краткое изложение алгоритма и навыков обхода PHP и краткое изложение навыков математических операций PHP

Я надеюсь, что эта статья будет полезна для программирования на PHP.